<?php
// +----------------------------------------------------------------------
// | Site:  [ http://www.yzmcms.com]
// +----------------------------------------------------------------------
// | Copyright: 袁志蒙工作室，并保留所有权利
// +----------------------------------------------------------------------
// | Author: YuanZhiMeng <214243830@qq.com>
// +---------------------------------------------------------------------- 
// | Explain: 这不是一个自由软件,您只能在不用于商业目的的前提下对程序代码进行修改和使用，不允许对程序代码以任何形式任何目的的再发布！
// +----------------------------------------------------------------------

defined('IN_YZMPHP') or exit('Access Denied'); 
yzm_base::load_controller('common', 'admin', 0);
yzm_base::load_sys_class('page','',0);
yzm_base::load_common('class/jst.class.php');
//yzm_base::load_common('plugin/easyTask/src/Task.php');
yzm_base::load_common('class/xlswriter.class.php');

class jst_manage extends common {

	/**
	 * 配置信息
	 */

	public $config;	
	public function __construct(){
		parent::__construct();
	}
	
	public function init() {

		//实时读取配置
		$data = D('config')->where(array('status'=>1))->select();
		$config = [];
		foreach($data as $val){
			$config[$val['name']] = $val['value'];
		}

		//获取access_token
		//if(!$config['jst_access_token']||!$config['jst_refresh_token']){
			$jst = new jst();
			$url = $jst->auth();
		//}
		
		//过期时间
		if($config['jst_access_token_expires_in']){
			$expires = date('Y-m-d H:i:s',$config['jst_access_token_expires_in']);
		}
		
		//快过期时可重新点击
		if($config['jst_access_token_expires_in']<time()-7*86400&&$config['jst_refresh_token']){
			$expires_btn = 1;
		}
		
		//雅鹿获取access_token
		$jst = new jst('_yalu');
		$yalu_url = $jst->auth();
		if($config['jst_yalu_access_token_expires_in']){
			$yalu_expires = date('Y-m-d H:i:s',$config['jst_yalu_access_token_expires_in']);
		}
		if($config['jst_yalu_access_token_expires_in']<time()-7*86400&&$config['jst_yalu_refresh_token']){
			$yalu_expires_btn = 1;
		}
		
		//安瑞井分仓库
		$jst = new jst('_anruijing');
		$anruijing_url = $jst->auth();
		if($config['jst_anruijing_access_token_expires_in']){
			$anruijing_expires = date('Y-m-d H:i:s',$config['jst_anruijing_access_token_expires_in']);
		}
		if($config['jst_anruijing_access_token_expires_in']<time()-7*86400&&$config['jst_anruijing_refresh_token']){
			$anruijing_expires_btn = 1;
		}
		
		//美丽衣橱分仓库
		$jst = new jst('_meiliyichu');
		$meiliyichu_url = $jst->auth();
		if($config['jst_meiliyichu_access_token_expires_in']){
			$meiliyichu_expires = date('Y-m-d H:i:s',$config['jst_meiliyichu_access_token_expires_in']);
		}
		if($config['jst_meiliyichu_access_token_expires_in']<time()-7*86400&&$config['jst_meiliyichu_refresh_token']){
			$meiliyichu_expires_btn = 1;
		}
		
		//美丽衣橱分仓库
		$jst = new jst('_qiaokeli');
		$qiaokeli_url = $jst->auth();
		if($config['jst_qiaokeli_access_token_expires_in']){
			$qiaokeli_expires = date('Y-m-d H:i:s',$config['jst_qiaokeli_access_token_expires_in']);
		}
		if($config['jst_qiaokeli_access_token_expires_in']<time()-7*86400&&$config['jst_qiaokeli_refresh_token']){
			$qiaokeli_expires_btn = 1;
		}
		
		//美丽衣橱分仓库
		$jst = new jst('_jeep');
		$jeep_url = $jst->auth();
		if($config['jst_jeep_access_token_expires_in']){
			$jeep_expires = date('Y-m-d H:i:s',$config['jst_jeep_access_token_expires_in']);
		}
		if($config['jst_jeep_access_token_expires_in']<time()-7*86400&&$config['jst_jeep_refresh_token']){
			$jeep_expires_btn = 1;
		}
		include $this->admin_tpl('jst/jst_manage');
	}
	
	/*店铺列表*/
	public function shop(){
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('id','nick','shop_id','shop_site','shop_name','is_enable')) ? $of : 'is_enable';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'DESC';
		$shop = D('jst_shop');
		$total = $shop->total();
		$page = new page($total, 100);
		$data = $shop->order("$of $or")->limit($page->limit())->select();
		include $this->admin_tpl('jst/jst_shop_list');
	}
	
	/*重新获取店铺列表*/
	public function get_shop(){
		//echo 111;exit;
		$jst = new jst('_anruijing');
		$result = $jst->shop();
		print_r($result);exit;
		if($result['code'] == 0){
			foreach($result['data']['datas'] as $v){
				$arr = [
					'nick' => $v['nick'],
					'shop_id' => $v['shop_id'],
					'shop_site' => $v['shop_site'],
					'shop_name' => $v['shop_name'],
				];
				$info = D('jst_shop')->where(array('shop_id' => $v['shop_id']))->find();
				if($info){
					D('jst_shop')->update($arr, array('shop_id'=>$v['shop_id']));
				}else{
					D('jst_shop')->insert($arr);
				}
			}
			return_json(array('status'=>1,'message'=>'获取成功！'));
		}else{
			return_json(array('status'=>0,'message'=>$result['msg']));
		}
	}
	
	/*仓库列表*/
	public function wms(){
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('id','nick','shop_id','shop_site','shop_name')) ? $of : 'id';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'ASC';
		$wms = D('jst_wms');
		$total = $wms->total();
		$page = new page($total, 100);
		$data = $wms->order("$of $or")->limit($page->limit())->select();
		include $this->admin_tpl('jst/jst_wms_list');
	}
	
	/*重新获取仓库列表*/
	public function get_wms(){
		$jst = new jst('_qiaokeli');
		$result = $jst->wms();
		print_r($result);exit;
		if($result['code'] == 0){
			foreach($result['data']['datas'] as $v){
				$arr = [
					'name' => $v['name'],
					'co_id' => $v['co_id'],
					'wms_co_id' => $v['wms_co_id'],
					'is_main' => $v['is_main']?1:0,
				];
				$info = D('jst_wms')->where(array('wms_co_id' => $v['wms_co_id']))->find();
				if($info){
					D('jst_wms')->update($arr, array('wms_co_id'=>$v['wms_co_id']));
				}else{
					D('jst_wms')->insert($arr);
				}
			}
			return_json(array('status'=>1,'message'=>'获取成功！'));
		}else{
			return_json(array('status'=>0,'message'=>$result['msg']));
		}
	}

	/*获取商品分类*/
	public function category(){
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('id','c_id','parent_c_id','modified','name')) ? $of : 'id';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'ASC';
		$wms = D('jst_category');
		$total = $wms->total();
		$page = new page($total, 100);
		$data = $wms->order("$of $or")->limit($page->limit())->select();
		include $this->admin_tpl('jst/jst_category_list');
	}
	
	/*获取聚水潭分类*/
	public function get_category(){
		return $this->jst_run('category','c_id');
	}
	
	/*批量获取*/
	public function ajax(){
		$type = $_GET['type'];
		//重新获取分类时，清空获取记录
		if($type=='category'){
			D('jst_log')->delete(['type'=>'category']);
		}
		if(!$type){
			return_json(array('status'=>0,'message'=>'type参数错误'));
		}
		include $this->admin_tpl('jst/jst_ajax');
	}

	/*重新获取仓库列表*/
	public function get_supplier(){
		$jst = new jst();
		//$arr = ['']
		$result = $jst->supplier();
		//var_dump($result);exit;
		if($result['code'] == 0){
			foreach($result['data']['datas'] as $v){
				$arr = [
					'supplier_id' => $v['supplier_id'],
					'supplier_code' => $v['supplier_code'],
					'name' => $v['name'],
					'group'=> $v['group'],
					'enabled'=> $v['enabled'],
					'remark'=>$v['remark'],
					'modified'=>strtotime($v['modified']),
				];
				$info = D('jst_supplier')->where(array('supplier_id' => $v['supplier_id']))->find();
				if($info){
					D('jst_supplier')->update($arr, array('supplier_id'=>$v['supplier_id']));
				}else{
					D('jst_supplier')->insert($arr);
				}
			}
			return_json(array('status'=>1,'message'=>'获取成功！'));
		}else{
			return_json(array('status'=>0,'message'=>$result['msg']));
		}
	}
	
	/*仓库列表*/
	public function supplier(){
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('id','supplier_id','supplier_code','name','is_enable','enable')) ? $of : 'is_enable';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'DESC';
		$jst_supplier = D('jst_supplier');
		$total = $jst_supplier->total();
		$page = new page($total, 100);
		$data = $jst_supplier->order("$of $or")->limit($page->limit())->select();
		//print_r($data);exit;
		include $this->admin_tpl('jst/jst_supplier_list');
	}
	
	/*仓库列表*/
	public function brand(){
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('id','name')) ? $of : 'is_enable';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'DESC';
		$jst_brand = D('jst_brand');
		$total = $jst_brand->total();
		$page = new page($total, 100);
		$data = $jst_brand->order("$of $or")->limit($page->limit())->select();
		include $this->admin_tpl('jst/jst_brand_list');
	}
	
	public function sales(){
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('id','date')) ? $of : 'id';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'DESC';
		$jst_sales = D('jst_sales');
		$total = $jst_sales->total();
		$page = new page($total, 100);
		$data = $jst_sales->order("$of $or")->limit($page->limit())->select();
		include $this->admin_tpl('jst/jst_sales_list');
	}
	
	/*定时器设置*/
	public function task(){
		$type = isset($_GET['type'])?$_GET['type']:'';
		$jst_task = D('jst_task');
		if($type){
			$info = ['id'=>'','name'=>'','time'=>'','process'=>'','url'=>''];
		}
		//添加
		if($type == 'add'){
			include $this->admin_tpl('jst/jst_task_add');
			return;
		}else if($type == 'edit'){//编辑
			$info = $jst_task->where(['id'=>$_GET['id']])->find();
			include $this->admin_tpl('jst/jst_task_add');
			return;
		}else if($type == 'action_add'){//确定添加/编辑
			$id = $_GET['id'];
			if($id){
				$res = $jst_task->update($_GET,['id'=>$_GET['id']]);
			}else{
				$res = $jst_task->insert($_GET);
			}
		}else if($type == 'del'){//删除
			$jst_task->delete(['id'=>$_GET['id']]);
		}else if($type == 'delcache'){//更新缓存
			redis_delcache('task');
			$res = get_task('task');
		}
		//变更任务更新缓存
		if($type == 'action_add' || $type == 'del'){
			redis_delcache('task');
			get_task();
		}
		if($type){
			if($res){
				return_json(array('status'=>1,'message'=>'操作成功'));
			}else{
				return_json(array('status'=>0,'message'=>'添加失败'));
			}
		}
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('id','date')) ? $of : 'id';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'DESC';
		
		$total = $jst_task->total();
		$page = new page($total, 100);
		$data = $jst_task->order("$of $or")->limit($page->limit())->select();
		include $this->admin_tpl('jst/jst_task');
	}
	
	
	/**
	 * 禁用启用
	 */
	public function change_status() {
		$type = $_GET['type'];
		if(!$type){
			return_json(array('status'=>0,'message'=>'type参数错误'));
		}
		if(is_post()){
			$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
			$value = isset($_POST['value']) ? intval($_POST['value']) : 0;
			$field = isset($_POST['field']) ? intval($_POST['field']) : 'is_enable';
			if(D('jst_'.$type)->update(array($field=>$value), array('id' => $id))){
				//更新缓存
				if($type == 'shop'){
					delcache('shop_ids');
					shop_ids();
				}else if($type == 'wms'){
					delcache('wms_co_ids');
					wms_co_ids();	
				}else if($type == 'brand'){
					delcache('brand_names');
					brand_names();
				}else if($type == 'task'){
					redis_delcache('task');
					get_task();
				}
				return_json(array('status'=>1,'message'=>L('operation_success')));
			}else{
				return_json();
			}
		}
	}
	
	/*快速编辑*/
	public function public_category_fast_edit(){
		$id = input('post.pk', 0, 'intval');
		$value = input('post.value', 0, 'intval');
		$name = input('post.name');
		if(!$id) return_json(array('status'=>0, 'message'=>L('illegal_parameters')));	
		$db = D('jst_category');
		$db->update(array($name=>$value), array('id'=>$id));
		return_json(array('status'=>1, 'message'=>L('operation_success')));	
	}
	
	/*商品列表*/
	public function sku(){
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('id','sku_id','i_id','enabled','modified','created','add_time','1days','2days','3days','7days','30days')) ? $of : 'id';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'ASC';
		$enabled = isset($_GET["enabled"]) ? $_GET["enabled"] : 99;
		$brand = isset($_GET["brand"]) ? $_GET["brand"] : '';
		$download = isset($_GET['download']) ? $_GET['download'] : 0;
		$show_type = isset($_GET['show_type']) ? $_GET['show_type'] : 1;
		$sku = D('jst_sku_sales');
		if($brand){
			$brand = str_replace('+',' ',$brand);
		}
		
		$where = '1=1';
		if(isset($_GET['dosubmit'])){	
			$i_id = isset($_GET["i_id"]) ? $_GET["i_id"] : '';
			$sku_id = isset($_GET["sku_id"]) ? $_GET["sku_id"] : '';
			$sku_code = isset($_GET["sku_code"]) ? $_GET["sku_code"] : '';
			$other_2 = isset($_GET["other_2"]) ? trim($_GET["other_2"]) : '';
			$properties_value = isset($_GET['properties_value']) ? safe_replace(trim($_GET['properties_value'])) : '';
			$name = isset($_GET["name"]) ? trim($_GET["name"]) : '';
			
			$c_id = isset($_GET["c_id"]) ? $_GET["c_id"] : '';
			$category_name = isset($_GET["category_name"]) ? $_GET["category_name"] : '';
			if($i_id) {
				if(strpos($i_id,'*') !== false){
					$i_id = trim($i_id,'*');
					$where .= ' AND i_id LIKE \'%'.$i_id.'%\'';
				}else{
					$where .= ' AND i_id = "'.$i_id.'"';
				}
			}
			if($sku_id) {
				if(strpos($sku_id,'*') !== false){
					$sku_id = trim($sku_id,'*');
					$where .= ' AND sku_id LIKE \'%'.$sku_id.'%\'';
				}else{
					$where .= ' AND sku_id = "'.$sku_id.'"';
				}
			}
			if($sku_code) {
				$where .= ' AND sku_code = "'.$sku_code.'"';
			}
			if($other_2){
				$where .=' AND other_2 LIKE \'%'.$other_2.'%\'';
			}
			if($properties_value) {
				$where .= ' AND properties_value LIKE \'%'.$properties_value.'%\'';
			}
			if($name) {
				$where .= ' AND name LIKE \'%'.$name.'%\'';
			}
			if($c_id) {
				$where .= ' AND c_id ='.$c_id;
			}
			if($category_name) {
				$category_name = explode('--',$category_name);
				$where .= ' AND category ="'.$category_name[0].'"';
			}
		}
		if(isset($enabled)) {
			if($enabled != 99){
				$where .= ' AND enabled = '.$enabled;
			}
		}
		if($brand) {
			$brand_arr = explode(',',$brand);
			$brand_arr = implode('","',$brand_arr);
			$where .= ' AND brand in ("'.$brand_arr.'")';
		}else{
			$str = [];
			foreach(brand_names() as $v){
				$str[] = '"'.$v.'"';
			}
			$where .= ' AND brand in('.implode(',',$str).')';
		}
		if($show_type == 1){
			$total = $sku->where($where)->total();
		}else{
			$total = $sku->field('count(distinct i_id)')->where($where)->one();
		}
		
		
		if($download==0){
			$page = new page($total, 100);
			if($show_type == 1){
				$data = $sku->where($where)->limit($page->limit())->order("$of $or")->select();
			}else{
				$data = $sku->field('pic,id,sku_id,sku_code,name,brand,labels,labels_brand,created,sales_add_time,i_id,other_2,properties_value,category,enabled,modified,sum(1days) 1days,sum(2days) 2days,sum(3days) 3days,sum(7days) 7days,sum(30days) 30days')->where($where)->limit($page->limit())->order("$of $or")->group('i_id')->select();
			}
			include $this->admin_tpl('jst/jst_sku_list');
		}else{
			$number = 50000;
			$page = ceil($total/$number);
			$excel = new xlswriter('sku',1);
			$excel->page();
			for($i=1;$i<=$page;$i++){
				$limit = ($i-1)*$number.','.$number;
				$data = $sku->where($where)->order("$of $or")->limit($limit)->select();
				$excel->insert_data($data);
				unset($data);
			}
			$excel->output();
		}
	}

	//库存列表
	public function inventorys(){
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('id','qty','virtual_qty','purchase_qty','return_qty','in_qty','pick_lock','order_lock','defective_qty')) ? $of : 'id';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'ASC';
		$inventorys = D('jst_inventorys');
		$download = isset($_GET['download']) ? $_GET['download'] : 0;
		$where = '1=1';
		$brand = isset($_GET["brand"]) ? $_GET["brand"] : '';
		if(isset($_GET['dosubmit'])){	
			$i_id = isset($_GET["i_id"]) ? $_GET["i_id"] : '';
			$sku_id = isset($_GET["sku_id"]) ? $_GET["sku_id"] : '';
			$sku_code = isset($_GET["sku_code"]) ? $_GET["sku_code"] : '';
			$properties_value = isset($_GET['properties_value']) ? safe_replace(trim($_GET['properties_value'])) : '';
			$sku_name = isset($_GET["name"]) ? $_GET["name"] : '';
			$other_2 = isset($_GET["other_2"]) ? $_GET["other_2"] : '';
			if($brand){
				$brand = str_replace('+',' ',$brand);
			}
		
			if($i_id) {
				if(strpos($i_id,'*') !== false){
					$i_id = trim($i_id,'*');
					$where .= ' AND i.i_id LIKE \'%'.$i_id.'%\'';
				}else{
					$where .= ' AND i.i_id = "'.$i_id.'"';
				}
			}
			if($sku_id) {
				if(strpos($sku_id,'*') !== false){
					$sku_id = trim($sku_id,'*');
					$where .= ' AND i.sku_id LIKE \'%'.$sku_id.'%\'';
				}else{
					$where .= ' AND i.sku_id = "'.$sku_id.'"';
				}
			}
			if($sku_code) {
				$where .= ' AND i.sku_code = "'.$sku_code.'"';
			}
			if($properties_value) {
				$where .= ' AND i.properties_value LIKE \'%'.$properties_value.'%\'';
			}
			if($sku_name) {
				$where .= ' AND i.sku_name LIKE \'%'.$sku_name.'%\'';
			}
			if($other_2) {
				$where .= ' AND i.other_2 LIKE \'%'.$other_2.'%\'';
			}
			if($brand) {
				$brand_arr = explode(',',$brand);
				$brand_arr = implode('","',$brand_arr);
				$where .= ' AND i.brand in ("'.$brand_arr.'")';
			}else{
				$str = [];
				foreach(brand_names() as $v){
					$str[] = '"'.$v.'"';
				}
				$where .= ' AND i.brand in('.implode($str,',').')';
			}
		}
		
		$total = $inventorys->alias('i')->where($where)->total();
		//判断是否是导出数据
		if($download==0){
			$page = new page($total, 100);
			$field = 'i.*,s.pic';
			$data = $inventorys->alias('i')->field($field)->join('yzm_jst_sku s on s.sku_id = i.sku_id','left')->where($where)->limit($page->limit())->order("i.$of $or")->select();
			$sum_qty = $inventorys->alias('i')->field('sum(qty)')->where($where)->one();
			$sum_virtual_qty = $inventorys->alias('i')->field('sum(virtual_qty)')->where($where)->one();
			include $this->admin_tpl('jst/jst_inventorys_list');
			
		}else{
			$number = 50000;
			$page = ceil($total/$number);
			$excel = new xlswriter('inventorys',1);
			$excel->page();
			for($i=1;$i<=$page;$i++){
				$limit = ($i-1)*$number.','.$number;
				$data = $inventorys->alias('i')->field('id,sku_id,i_id,brand,sku_name,other_2,qty,order_lock,pick_lock,virtual_qty,purchase_qty,return_qty,in_qty,defective_qty')->where($where)->order("$of $or")->limit($limit)->select();
				$excel->insert_data($data);
				unset($data);
			}
			$excel->output();
		}
	}
	
	//执行全量商品更新
	public function inventorys_update(){
		if(getcache('LOCK::inventorys_update_run')){
			return_json(array('status'=>0,'message'=>'后台已在重新获取库存，请勿重复执行！'));
		}
		$get = $_GET;
		$where = '1=1';
		$i_id = isset($_GET["i_id"]) ? $_GET["i_id"] : '';
		$sku_id = isset($_GET["sku_id"]) ? $_GET["sku_id"] : '';
		$sku_code = isset($_GET["sku_code"]) ? $_GET["sku_code"] : '';
		$other_2 = isset($_GET["other_2"]) ? trim($_GET["other_2"]) : '';
		$properties_value = isset($_GET['properties_value']) ? safe_replace(trim($_GET['properties_value'])) : '';
		$name = isset($_GET["name"]) ? trim($_GET["name"]) : '';
		$brand = isset($_GET["brand"]) ? $_GET["brand"] : '';
		$c_id = isset($_GET["c_id"]) ? $_GET["c_id"] : '';
		if($i_id) {
			if(strpos($i_id,'*') !== false){
				$i_id = trim($i_id,'*');
				$where .= ' AND i_id LIKE \'%'.$i_id.'%\'';
			}else{
				$where .= ' AND i_id = "'.$i_id.'"';
			}
		}
		if($sku_id) {
			if(strpos($sku_id,'*') !== false){
				$sku_id = trim($sku_id,'*');
				$where .= ' AND sku_id LIKE \'%'.$sku_id.'%\'';
			}else{
				$where .= ' AND sku_id = "'.$sku_id.'"';
			}
		}
		if($sku_code) {
			$where .= ' AND sku_code = "'.$sku_code.'"';
		}
		if($other_2){
			$where .=' AND other_2 LIKE \'%'.$other_2.'%\'';
		}
		if($properties_value) {
			$where .= ' AND properties_value LIKE \'%'.$properties_value.'%\'';
		}
		if($name) {
			$where .= ' AND name LIKE \'%'.$name.'%\'';
		}
		if($c_id) {
			$where .= ' AND c_id ='.$c_id;
		}
		if($brand) {
			$brand_arr = explode(',',$brand);
			$brand_arr = implode('","',$brand_arr);
			$where .= ' AND brand in ("'.$brand_arr.'")';
		}else{
			$str = [];
			foreach(brand_names() as $v){
				$str[] = '"'.$v.'"';
			}
			$where .= ' AND brand in('.implode($str,',').')';
		}
		$res1 = D('jst_sku')->update(['is_syn'=>0],$where);
		//echo D('jst_sku')->lastsql();
		$res2 = D('config')->update(['value'=>1], ['name'=>'jst_update_inventory']);
		$res3 = D('config')->update(['value'=>1], ['name'=>'jst_update_inventory_yalu']);
		$res4 = D('config')->update(['value'=>1], ['name'=>'jst_update_inventory_anruijing']);
		$res5 = D('config')->update(['value'=>1], ['name'=>'jst_update_inventory_meiliyichu']);
		$res6 = D('config')->update(['value'=>1], ['name'=>'jst_update_inventory_jeep']);
		$res7 = D('config')->update(['value'=>1], ['name'=>'jst_update_inventory_qiaokeli']);
		delcache('configs');
		if($res1!==false&&$res2!==false&&$res3!==false&&$res4!==false&&$res5!==false&&$res6!==false&&$res7!==false){
			delcache('LOCK::get_inventorys_yalu');
			delcache('LOCK::get_inventorys_anruijing');
			delcache('LOCK::get_inventorys_meiliyichu');
			delcache('LOCK::get_inventorys_jeep');
			delcache('LOCK::get_inventorys_qiaokeli');
			delcache('LOCK::get_inventorys');
			//锁半天
			//setcache('LOCK::inventorys_update_run',1,3600);
			return_json(array('status'=>1,'message'=>'操作成功，已在后台执行获取库存！'));
		}else{
			return_json(array('status'=>0,'message'=>'执行失败，请联系管理员！'));
		}
	}
	
	//执行重新获取商品
	public function sku_update(){
		
		$enabled = isset($_GET["enabled"]) ? $_GET["enabled"] : 99;
		$brand = isset($_GET["brand"]) ? $_GET["brand"] : '';
		$sku = D('jst_sku');
		if($brand){
			$brand = str_replace('+',' ',$brand);
		}
		
		$where = '1=1';
		$i_id = isset($_GET["i_id"]) ? $_GET["i_id"] : '';
		$sku_id = isset($_GET["sku_id"]) ? $_GET["sku_id"] : '';
		$sku_code = isset($_GET["sku_code"]) ? $_GET["sku_code"] : '';
		$other_2 = isset($_GET["other_2"]) ? trim($_GET["other_2"]) : '';
		$properties_value = isset($_GET['properties_value']) ? safe_replace(trim($_GET['properties_value'])) : '';
		$name = isset($_GET["name"]) ? trim($_GET["name"]) : '';
		
		$c_id = isset($_GET["c_id"]) ? $_GET["c_id"] : '';
		$category_name = isset($_GET["category_name"]) ? $_GET["category_name"] : '';
		if($i_id) {
			if(strpos($i_id,'*') !== false){
				$i_id = trim($i_id,'*');
				$where .= ' AND i_id LIKE \'%'.$i_id.'%\'';
			}else{
				$where .= ' AND i_id = "'.$i_id.'"';
			}
		}
		if($sku_id) {
			if(strpos($sku_id,'*') !== false){
				$sku_id = trim($sku_id,'*');
				$where .= ' AND sku_id LIKE \'%'.$sku_id.'%\'';
			}else{
				$where .= ' AND sku_id = "'.$sku_id.'"';
			}
		}
		if($sku_code) {
			$where .= ' AND sku_code = "'.$sku_code.'"';
		}
		if($other_2){
			$where .=' AND other_2 LIKE \'%'.$other_2.'%\'';
		}
		if($properties_value) {
			$where .= ' AND properties_value LIKE \'%'.$properties_value.'%\'';
		}
		if($name) {
			$where .= ' AND name LIKE \'%'.$name.'%\'';
		}
		if($c_id) {
			$where .= ' AND c_id ='.$c_id;
		}
		if($category_name) {
			$category_name = explode('--',$category_name);
			$where .= ' AND category ="'.$category_name[0].'"';
		}
		if(isset($enabled)) {
			if($enabled != 99){
				$where .= ' AND enabled = '.$enabled;
			}
		}
		if($brand) {
			$brand_arr = explode(',',$brand);
			$brand_arr = implode('","',$brand_arr);
			$where .= ' AND brand in ("'.$brand_arr.'")';
		}else{
			$str = [];
			foreach(brand_names() as $v){
				$str[] = '"'.$v.'"';
			}
			$where .= ' AND brand in('.implode($str,',').')';
		}
		
		if(getcache('LOCK::get_update_sku_run')){
			return_json(array('status'=>0,'message'=>'后台已在更新商品信息，请勿重复执行！'));
		}
		$res = D('jst_sku')->where($where)->update(['add_time'=>0],'1');
		if($res!==false){
			//锁半天
			setcache('LOCK::jst_sku_update',1,3600);
			setcache('LOCK::jst_sku_update_jeep',1,3600);
			return_json(array('status'=>1,'message'=>'操作成功，已在后台执行更新商品信息！'));
		}else{
			return_json(array('status'=>0,'message'=>'执行失败，请联系管理员！'));
		}
	}
	
	
	//订单列表
	public function orders(){
		//输入参数初始化
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('o.id','o.o_id','o.so_id','o.order_date','o.add_time')) ? $of : 'o.order_date';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'DESC';
		$enabled = isset($_GET["enabled"]) ? $_GET["enabled"] : 1;
		$orders = D('jst_orders');
		$where = '1=1';
		$time_type = isset($_GET["time_type"]) ? $_GET["time_type"] : 0;
		//如果没有输入值，默认查询近7天
		$start = isset($_GET["start"]) ? $_GET["start"] : date("Y-m-d",strtotime("-7 day"));
		$end = isset($_GET["end"]) ? $_GET["end"] : date('Y-m-d');
		$download = isset($_GET['download']) ? $_GET['download'] : 0;
		$order_status = isset($_GET["order_status"]) ? $_GET["order_status"] : '';
		$shop_id = isset($_GET["shop_id"]) ? $_GET["shop_id"] : '';
		$o_id = isset($_GET["o_id"]) ? $_GET["o_id"] : '';

		//订单时间
		if($time_type == 0 && $start && $end){
			$where .= ' AND o.order_date >='.strtotime($start).' AND o.order_date<'.(strtotime($end)+86400);
		}
		//发货时间
		if($time_type == 1 && $start && $end){
			$where .= ' AND o.send_date >='.strtotime($start).' AND o.send_date<'.(strtotime($end)+86400);
		}
		if(isset($_GET['dosubmit'])){
			//搜索
			$i_id = isset($_GET["i_id"]) ? $_GET["i_id"] : '';
			$sku_id = isset($_GET["sku_id"]) ? $_GET["sku_id"] : '';
			$sku_code = isset($_GET["sku_code"]) ? $_GET["sku_code"] : '';
			$properties_value = isset($_GET['properties_value']) ? safe_replace(trim($_GET['properties_value'])) : '';
			$name = isset($_GET["name"]) ? $_GET["name"] : '';
			$brand = isset($_GET["brand"]) ? $_GET["brand"] : '';
			
			if(($start==''&&$end!='')||($start!=''&&$end=='')){
				showmsg('请输入开始时间/结束时间', 'stop');
				exit;
			}
			if($i_id) {
				if(strpos($i_id,'*') !== false){
					$i_id = trim($i_id,'*');
					$where .= ' AND oi.i_id LIKE \'%'.$i_id.'%\'';
				}else{
					$where .= ' AND oi.i_id = "'.$i_id.'"';
				}
			}
			if($sku_id) {
				if(strpos($sku_id,'*') !== false){
					$sku_id = trim($sku_id,'*');
					$where .= ' AND oi.sku_id LIKE \'%'.$sku_id.'%\'';
				}else{
					$where .= ' AND oi.sku_id = "'.$sku_id.'"';
				}
			}
			if($sku_code) {
				$where .= ' AND oi.sku_code = "'.$sku_code.'"';
			}
			if($properties_value) {
				$where .= ' AND oi.properties_value LIKE \'%'.$properties_value.'%\'';
			}
			if($name) {
				$where .= ' AND oi.sku_name LIKE \'%'.$name.'%\'';
			}
			if($shop_id) {
				$shop_arr = explode(',',$shop_id);
				$shop_arr = implode('","',$shop_arr);
				$where .= ' AND o.shop_id in ("'.$shop_arr.'")';
			}
			if($order_status){
				$order_status_arr = explode(',',$order_status);
				$order_status_arr = implode('","',$order_status_arr);
				$where .=' AND o.status in("'.$order_status_arr.'")';
			}
			if($o_id){
				$where .=" AND o.o_id = ".$o_id;
			}
		}
		
		//判断是否是导出数据
		if($download==0){
			$total = $orders->alias('o')->join('yzmcms_jst_orders_items oi ON o.o_id=oi.o_id and o.shop_id=oi.shop_id', 'left')->where($where)->total();
			$total_qty = $orders->alias('o')
				->field('sum(oi.qty) qty')
				->where($where)
				->join('yzmcms_jst_orders_items oi ON o.o_id=oi.o_id and o.shop_id=oi.shop_id', 'left')
				->one();
			$page = new page($total, 100);
			$data = $orders->alias('o')
				->field('o.*,sum(oi.qty) qty')
				->where($where)
				->join('yzmcms_jst_orders_items oi ON o.o_id=oi.o_id and o.shop_id=oi.shop_id', 'left')
				->limit($page->limit())
				->group('o.o_id')
				->order("$of $or")
				->select();
			include $this->admin_tpl('jst/jst_orders_list');
		}else{
			$number = 30000;
			$total = $orders->alias('o')->join('yzmcms_jst_orders_items oi ON o.o_id=oi.o_id and o.shop_id=oi.shop_id', 'left')->where($where)->total();
			$page = ceil($total/$number);
			$excel = new xlswriter('orders',1);
			//print_r($_SESSION);exit;
			for($i=1;$i<=$page;$i++){
				$limit = ($i-1)*$number.','.$number;
				$data = $orders->alias('o')
					->field('o.id,o.o_id,o.so_id,o.order_date,o.send_date,o.remark,o.labels,o.status,oi.sku_id,oi.properties_value,oi.qty,oi.sku_name')
					->where($where)
					->join('yzmcms_jst_orders_items oi ON o.o_id=oi.o_id and o.shop_id=oi.shop_id', 'left')
					->order("$of $or")
					->limit($limit)
					->select();
				setcache('data_'.$i,$data);
				unset($data);
			}
			$excel->output($page);
		}
	}
	
	public function orders_items(){
		if(!$_GET['o_id']&&$_GET['shop_id']){
			return;
		}
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('id')) ? $of : 'id';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'DESC';
		$orders_items = D('jst_orders_items');
		$where = '1=1 AND o_id='.$_GET['o_id'].' AND shop_id = '.$_GET['shop_id'];
		$total = $orders_items->where($where)->total();
		$total_qty = $orders_items
			->field('sum(qty) qty')
			->where($where)
			->one();
		$page = new page($total, 100);
		$data = $orders_items
			->where($where)
			->limit($page->limit())
			->order("$of $or")
			->select();
		include $this->admin_tpl('jst/jst_orders_items_list');
	}
	
	public function order_action(){
		$company = '';
		if(strpos($_GET['shop_name'],'雅鹿')!==false){
			$company = '_yalu';
		}else if(strpos($_GET['shop_name'],'安瑞井')!==false){
			$company = '_anruijing';
		}else if(strpos($_GET['shop_name'],'美丽衣橱')!==false){
			$company = '_meiliyichu';
		}else if(strpos($_GET['shop_name'],'ilovechoc')!==false){
			$company = '_qiaokeli';
		}else if(strpos($_GET['shop_name'],'MOYO')!==false){
			$company = '_anruijing';
		}else if(strpos($_GET['shop_name'],'JEEP')!==false){
			$company = '_jeep';
		}
		$jst = new jst($company);
		$arr = [
			'o_id' => $_GET['o_id'],
			"page_index" => 1,
			"page_size" => 300
		];
		$result = $jst->order_action($arr);
		$data = $result['data']['datas'];
		$total = count($data);
		include $this->admin_tpl('jst/jst_order_action');
	}
	
	
	/*唐狮补货数据格式化*/
	private function ts_buhuo_format($data){
		foreach($data as &$v){
			if(!$v['xt_qty']){
				$v['xt_qty'] = 0;
			}
			if(!$v['ts_qty']){
				$v['ts_qty'] = 0;
			}
			if(!$v['allocate_qty']){
				$v['allocate_qty'] = 0;
			}
			if(!$v['production_qty']){
				$v['production_qty'] = 0;
			}
			//补货数量
			//$need_buhuo = $v['7days'] - $v['ts_qty'];
			//如果需要补货
			if($v['need_buhuo']>0){
				if($v['xt_qty']>0){
					if($v['xt_qty']>$v['need_buhuo']){
						$v['buhuo_qty'] = $v['need_buhuo'];
					}else{
						$v['buhuo_qty'] = $v['xt_qty'].'-即将断货';
					}
				}else{
					$v['buhuo_qty'] = '断货';
				}
			}else{
				//不需要补货
				$v['buhuo_qty'] = '-';
			}
			//建议生产数=7天销量/7*（生产周期+1天查货时间）-新塘仓库存-唐狮仓库存-调拨途中库存-生产中的库存
			//$v['shengchan_qty'] = intval($v['7days']*($v['tj_cycel']+1)/7-$v['ts_qty']-$v['xt_qty']-$v['production_qty']);
			if(!$v['shengchan_qty']){
				$v['shengchan_qty'] = '-';
			}
			if($v['shengchan_qty']<0){
				$v['shengchan_qty'] = '-';
			}
			$v['today'] = D('jst_orders_items')->field('IFNULL(sum(qty),0)')->where('sku_id = "'.$v['sku_id'].'" AND status_code IN (2,4,7,8,9) AND order_date < unix_timestamp( NOW()) AND order_date >= unix_timestamp(CONCAT( CURDATE(), " 00:00:00" ))')->one();
		}
		return $data;
	}
	/*唐狮补货*/
	public function ts_buhuo(){
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('s.id','s.1days','s.2days','s.3days','s.7days','s.30days','i.qty','need_buhuo','shengchan_qty')) ? $of : 's.7days';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'DESC';
		$where = 's.brand="唐狮" and s.30days>0 and s.enabled=1';
		$download = isset($_GET['download']) ? $_GET['download'] : 0;
		$sku = D('jst_sku_sales');

		if(isset($_GET['dosubmit'])){	
			$i_id = isset($_GET["i_id"]) ? $_GET["i_id"] : '';
			$sku_id = isset($_GET["sku_id"]) ? $_GET["sku_id"] : '';
			$sku_code = isset($_GET["sku_code"]) ? $_GET["sku_code"] : '';
			$properties_value = isset($_GET['properties_value']) ? safe_replace(trim($_GET['properties_value'])) : '';
			$name = isset($_GET["name"]) ? $_GET["name"] : '';
			$c_id = isset($_GET["c_id"]) ? $_GET["c_id"] : '';
			if($i_id) {
				if(strpos($i_id,'*') !== false){
					$i_id = trim($i_id,'*');
					$where .= ' AND s.i_id LIKE \'%'.$i_id.'%\'';
				}else{
					$where .= ' AND s.i_id = "'.$i_id.'"';
				}
			}
			if($sku_id) {
				if(strpos($sku_id,'*') !== false){
					$sku_id = trim($sku_id,'*');
					$where .= ' AND s.sku_id LIKE \'%'.$sku_id.'%\'';
				}else{
					$where .= ' AND s.sku_id = "'.$sku_id.'"';
				}
			}
			if($sku_code) {
				$where .= ' AND s.sku_code = "'.$sku_code.'"';
			}
			if($properties_value) {
				$where .= ' AND s.properties_value LIKE \'%'.$properties_value.'%\'';
			}
			if($name) {
				$where .= ' AND s.name LIKE \'%'.$name.'%\'';
			}
			if($c_id) {
				$where .= ' AND s.c_id ='.$c_id;
			}
		}
		
		$xt_qty = 'IFNULL(i.qty,0)';//新塘仓库存
		$ts_qty = 'IFNULL(ii.qty,0)';//唐狮仓库存
		$allocate_qty = 'IFNULL(sum(ai.qty),0)';//调拨库存
		$production_qty = 'IFNULL(i.purchase_qty,0)';//生产中库存
		//建议生产数=7天销量/7*（生产周期+1天查货时间）-新塘仓库存-唐狮仓库存-调拨途中库存-生产中的库存
		$shengchan_qty = 'round(s.7days/7*(c.tj_cycel+1)-'.$xt_qty.'-'.$ts_qty.'-'.$allocate_qty.'-'.$production_qty.',0)';//建议生产
		$need_buhuo = 'if((s.7days-'.$ts_qty.')<1,0,s.7days-'.$ts_qty.')';
		if($download==0){
			$total = $sku->alias('s')->where($where)->total();
			$page = new page($total, 100);
			$data = $sku->alias('s')
				->field('s.*,'.$xt_qty.' xt_qty,'.$ts_qty.' ts_qty,'.$allocate_qty.' allocate_qty,'.$production_qty.' production_qty,c.tj_cycel,'.$need_buhuo.' need_buhuo,'.$shengchan_qty.' shengchan_qty')
				->join('yzmcms_jst_inventorys i ON i.sku_id=CONCAT("TJ-",s.sku_code)', 'left')
				->join('yzmcms_jst_inventorys ii ON ii.sku_id=s.sku_id', 'left')
				->join('yzmcms_jst_allocate_items ai ON s.sku_id=ai.sku_id', 'left')
				->join('yzmcms_jst_category c on s.c_id = c.c_id','left')
				->order("$of $or")
				->where($where)->limit($page->limit())->group('s.sku_id')
				//->order("$of $or")
				->select();
			$data = $this->ts_buhuo_format($data);
			include $this->admin_tpl('jst/jst_ts_buhuo');
		}else{
			$number = 30000;
			$total = $sku->alias('s')->where($where)->total();
			$page = ceil($total/$number);
			$excel = new xlswriter('ts_buhuo',1);
			//print_r($_SESSION);exit;
			for($i=1;$i<=$page;$i++){
				$limit = ($i-1)*$number.','.$number;
				$data = $sku->alias('s')
					->field('s.*,'.$xt_qty.' xt_qty,'.$ts_qty.' ts_qty,'.$allocate_qty.' allocate_qty,'.$production_qty.' production_qty,c.tj_cycel,s.7days-'.$ts_qty.' need_buhuo,'.$shengchan_qty.' shengchan_qty')
					->join('yzmcms_jst_inventorys i ON i.sku_id=CONCAT("TJ-",s.sku_code)', 'left')
					->join('yzmcms_jst_inventorys ii ON ii.sku_id=s.sku_id', 'left')
					->join('yzmcms_jst_allocate_items ai ON s.sku_id=ai.sku_id', 'left')
					->join('yzmcms_jst_category c on s.c_id = c.c_id')
					->order("$of $or")
					->where($where)->group('s.sku_id')
					//->order("$of $or")
					->select();
				$data = $this->ts_buhuo_format($data);
				setcache('data_'.$i,$data);
				unset($data);
			}
			$excel->output($page);
		}
	}	
	
	/*佑晟找款*/
	public function ys_zhaokuan(){
		$type = isset($_GET['type']) ? $_GET['type'] : '';
		//颜色输入款，预选列表
		if($type == 'get_color'){
			$field = 'SUBSTRING_INDEX( properties_value, ";", 1 )';
			$list = D('jst_sku')->field($field.' color')->where('properties_value<>"" and properties_value like "%'.$_GET['color'].'%"')->order('CHAR_LENGTH('.$field.') asc')->group($field)->select();
			if($list){
				return_json(array('status'=>1,'message'=>L('operation_success'),'data'=>$list));
			}else{
				return_json(array('status'=>0,'message'=>''));
			}
		}
		//输入框，预选列表
		if($type == 'get_ups'){
			$list = D('jst_sku_ups')->field('pv_value')->where('pv_value like "%'.$_GET['ups'].'%"')->order('CHAR_LENGTH(pv_value) asc')->group('pv_value')->select();
			if($list){
				return_json(array('status'=>1,'message'=>L('operation_success'),'data'=>$list));
			}else{
				return_json(array('status'=>0,'message'=>''));
			}
		}
		//删除成份数据
		if($type == 'del'){
			D('jst_sku_ups')->delete(['id'=>$_GET['id']]);
		}
		//添加面料成份
		if($type == "add"){
			$id = $_GET['id'];
			$info = D('jst_sku_ups')->field('pv_value,ups_sku_name')->where(['id'=>$id])->find();
			include $this->admin_tpl('jst/jst_ys_zhaokuan_add');
			exit;
		}
		//提交添加面料成份
		if($type == 'action_add'){
			$id = $_GET['id'];
			//去除所有空白字符
			$pv_value = preg_replace("/\s|　/","",$_GET['pv_value']);
			$ups_sku_name = preg_replace("/\s|　/","",$_GET['ups_sku_name']);
			$sku_ups = D('jst_sku_ups')->field('i_id,pv_value')->where(['id'=>$id])->find();
			if($pv_value == $sku_ups['pv_value']){
				return_json(array('status'=>0,'message'=>'面料成份已经存在！'));
			}
			$insert_data = [
				'i_id' => $sku_ups['i_id'],
				'p_name' => '面料成份',
				'pv_value' => $pv_value,
				'ups_sku_name' => $ups_sku_name,
				'add_time' => time()
			];
			$res = D('jst_sku_ups')->insert($insert_data);
			if($res){
				return_json(array('status'=>1,'message'=>'操作成功'));
			}else{
				return_json(array('status'=>0,'message'=>'添加失败'));
			}
		}
		$of = input('get.of');
		$or = input('get.or');
		$enabled = isset($_GET["enabled"]) ? $_GET["enabled"] : 99;
		$ups = isset($_GET["ups"]) ? $_GET["ups"] : '';
		$color = isset($_GET["properties_value"]) ? $_GET["properties_value"] : '';
		$brand = isset($_GET["brand"]) ? $_GET["brand"] : '';
		$is_ys = isset($_GET['is_ys']) ? $_GET['is_ys']:1;//是否只筛选佑晟公司品牌
		$sku_ups = D('jst_sku_ups');
		if($brand){
			$brand = str_replace('+',' ',$brand);
		}
		
		$where = '1=1';
		if(isset($_GET['dosubmit'])){
			$i_id = isset($_GET["i_id"]) ? $_GET["i_id"] : '';
			$sku_id = isset($_GET["sku_id"]) ? $_GET["sku_id"] : '';
			$name = isset($_GET["name"]) ? $_GET["name"] : '';
			$c_id = isset($_GET["c_id"]) ? $_GET["c_id"] : '';
			if($i_id) {
				if(strpos($i_id,'*') !== false){
					$i_id = trim($i_id,'*');
					$where .= ' AND su.i_id LIKE \'%'.$i_id.'%\'';
				}else{
					$where .= ' AND su.i_id = "'.$i_id.'"';
				}
			}
			if($sku_id) {
				if(strpos($sku_id,'*') !== false){
					$sku_id = trim($sku_id,'*');
					$where .= ' AND s.sku_id LIKE \'%'.$sku_id.'%\'';
				}else{
					$where .= ' AND s.sku_id = "'.$sku_id.'"';
				}
			}
			if($name) {
				$where .= ' AND s.name LIKE \'%'.$name.'%\'';
			}
			if($c_id) {
				$where .= ' AND s.c_id ='.$c_id;
			}
		}
		if(isset($enabled)) {
			if($enabled != 99){
				$where .= ' AND s.enabled = '.$enabled;
			}
		}
		if($brand) {
			$where .= ' AND s.brand = "'.$brand.'"';
		}else if($is_ys){
			$where .= ' AND s.brand in("东方骆驼","增致牛仔 ZENGZHI","米菲 MIFFY","雅鹿","佑晟共享仓","安瑞井","MOYO","琴曼","美丽衣橱","GOOGIMS","ICE","JEEP")';
		}
		if($color){
			$where .=' and SUBSTRING_INDEX( s.properties_value, ";", 1) like "%'.$color.'%"';
		}
		if($ups){
			//百分号转义
			$ups = str_replace("%", "\%", $ups);
			$where .=' and su.pv_value like "%'.$ups.'%"';
		}
		$where .=' and su.p_name="面料成份"';
		$total = $sku_ups->alias('su')->field('count(DISTINCT CONCAT(s.name,SUBSTRING_INDEX( s.properties_value, ";", 1 ),su.pv_value))')->join('yzmcms_jst_sku s ON s.i_id=su.i_id', 'left')->where($where)->one();
		$page = new page($total, 100);
		$data = $sku_ups->alias('su')->field('s.i_id,su.id,su.p_id,su.ups_sku_name,s.pic,s.sku_code,s.name,SUBSTRING_INDEX( s.properties_value, ";", 1) color,s.brand,s.category,su.pv_value,s.enabled,s.modified,s.add_time,su.add_time su_add_time')->join('yzmcms_jst_sku s ON s.i_id=su.i_id', 'left')->where($where)->limit($page->limit())->group('CONCAT(s.NAME,SUBSTRING_INDEX(s.properties_value,";",1 ),su.pv_value)')->select();
		include $this->admin_tpl('jst/jst_ys_zhaokuan');
	}
	
	/*佑晟订做*/
	public function ys_dingzuo(){
		$company='';
		$url = U('ys_dingzuo');
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('other_2','sum_1days','sum_2days','sum_3days','sum_7days','sum_30days','total_qty','purchase_total_qty','buhuo_total_qty')) ? $of : 'sum_7days';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'DESC';
		$buhuo_by_days = isset($_GET['buhuo_by_days']) ? $_GET['buhuo_by_days'] : '3';
		$download = isset($_GET['download']) ? $_GET['download'] : 0;
		$where = '';
		if(isset($_GET['other_2'])&&trim($_GET['other_2'])){
			$where = ' and other_2 like "%'.trim($_GET['other_2']).'%"';
		}
		$where_name = '';
		if(isset($_GET['sku_name'])&&trim($_GET['sku_name'])){
			$where_name = ' and name like "%'.trim($_GET['sku_name']).'%"';
		}
		
		//订做商品库存列表
		$dingzuo_invertorys = D('jst_inventorys')->field('other_2,sum(qty) qty,substring_index(other_2,"#",1) kuanhao')->where('other_2 like "订做%"'.$where)->group('other_2')->select();
		
		//采购商品库存，采用共享仓订做商品编码
		$dingzuo_purchase = D('jst_inventorys')->field('other_2,purchase_qty,sku_id,brand,substring_index(other_2,"#",1) kuanhao')->where('other_2 like "订做%" and purchase_qty>0 and brand="佑晟共享仓"'.$where)->select();
		//print_r($dingzuo_invertorys);exit;
		$kucun_temp = [];
		if($dingzuo_purchase){
			foreach($dingzuo_purchase as $val){
				$other_2 = explode('#',$val['other_2']);
				//多个供应商商品编码不一致，需要累加
				if(isset($kucun_temp[$val['other_2']]['purchase_qty'])){
					$kucun_temp[$val['other_2']]['purchase_qty'] += $val['purchase_qty'];
				}else{
					$kucun_temp[$val['other_2']]['purchase_qty'] = $val['purchase_qty'];
				}
				
				if(isset($kucun_temp[$val['kuanhao']]['purchase_total_qty'])){
					$kucun_temp[$val['kuanhao']]['purchase_total_qty'] += $val['purchase_qty'];
				}else{
					$kucun_temp[$val['kuanhao']]['purchase_total_qty'] = $val['purchase_qty'];
				}
			}
		}
//print_r($kucun_temp);exit;
		if($dingzuo_invertorys){
			foreach($dingzuo_invertorys as $v){
				if(strpos($v['other_2'],'#')==false){
					exit('商品资料错误：'.$v['other_2']);
				}
				//$sku_name = md5(explode('#',$v['other_2'])[0]);
				//$properties_value = md5()
				if(isset($kucun_temp[$v['kuanhao']]['total_qty'])){
					$kucun_temp[$v['kuanhao']]['total_qty'] += $v['qty'];
				}else{
					$kucun_temp[$v['kuanhao']]['total_qty'] = $v['qty'];
				}
				$kucun_temp[$v['other_2']]['qty'] = $v['qty'];
			}
		}
		
		
		unset($dingzuo_invertorys);
		unset($dingzuo_purchase);
		
		//销售汇总根据店铺+款号
		$brand_kuanhao_list = D('jst_sku_sales')->alias('s')
			->field('s.other_2,sum(s.1days) sum_1days,sum(s.2days) sum_2days,sum(s.3days) sum_3days,sum(s.7days) sum_7days,sum(s.30days) sum_30days,substring_index(s.other_2,"#",1) kuanhao,CONCAT(s.brand,s.other_2) brand_kuanhao,s.brand')
			->where("s.other_2 like '订做%' and s.brand in ('佑晟共享仓','东方骆驼','增致牛仔 ZENGZHI','增致牛仔 ZENGZHI','雅鹿') and s.enabled = 1 ".$where)
			->group('CONCAT(s.brand,s.other_2)')
			->select();
			
		
		//所有定制商品列表
		$all_list = D('jst_sku_sales')->alias('s')
			->field('s.other_2,s.1days,s.2days,s.3days,s.7days,s.30days,substring_index(s.other_2,"#",1) kuanhao,s.brand,s.pic,s.c_id,s.sales_add_time,name')
			->where("s.other_2 like '订做%' and s.brand in ('佑晟共享仓','东方骆驼','增致牛仔 ZENGZHI','雅鹿')".$where.$where_name)
			->select();

		//补货周期
		$category_list = D('jst_category')->field('c_id,cycel')->select();
		$cycel_temp = [];
		foreach($category_list as $category){
			$cycel_temp[$category['c_id']] = $category['cycel'];
		}
			
		if($brand_kuanhao_list){
			$brand_kuanhao_temp = [];
			foreach($brand_kuanhao_list as $k=>$brand_kuanhao){
				if($brand_kuanhao['brand'] == '佑晟共享仓'){
					continue;
				}
				$brand_kuanhao_temp[$brand_kuanhao['other_2']][$brand_kuanhao['brand']] = $brand_kuanhao;
			}
		}
//print_r($all_list);exit;
		if($all_list){
			$list = [];
			$other_2_sum = [];
			foreach($all_list as $v){
				/*款号统计资料*/
				//图片
				$list[$v['kuanhao']]['pic'] = $v['pic'];
				$list[$v['kuanhao']]['name'] = $v['name'];
				if(!isset($list[$v['kuanhao']]['sales_add_time'])&&$v['sales_add_time']){
					$list[$v['kuanhao']]['sales_add_time'] = $v['sales_add_time'];
				}
				if($v['sales_add_time']){
					$list[$v['kuanhao']]['sales_add_time'] = isset($list[$v['kuanhao']]['sales_add_time']) ? $list[$v['kuanhao']]['sales_add_time'] : 0;
					if($v['sales_add_time']>$list[$v['kuanhao']]['sales_add_time']){
						$list[$v['kuanhao']]['sales_add_time'] =   $v['sales_add_time'];
					}
				}
				
				//款号库存总和
				if(!isset($list[$v['kuanhao']]['kucun'])){
					$list[$v['kuanhao']]['total_qty'] = isset($kucun_temp[$v['kuanhao']]['total_qty'])?$kucun_temp[$v['kuanhao']]['total_qty']:0;
				}
				//款号生产中的库存总和
				if(!isset($list[$v['kuanhao']]['purchase_total_qty'])){
					$list[$v['kuanhao']]['purchase_total_qty'] = isset($kucun_temp[$v['kuanhao']]['purchase_total_qty'])?$kucun_temp[$v['kuanhao']]['purchase_total_qty']:0;
				}
				//款号销量合计
				if(isset($list[$v['kuanhao']]['sum_1days'])){
					$list[$v['kuanhao']]['sum_1days'] += $v['1days'];
				}else{
					$list[$v['kuanhao']]['sum_1days'] = $v['1days'];
				}
				if(isset($list[$v['kuanhao']]['sum_2days'])){
					$list[$v['kuanhao']]['sum_2days'] += $v['2days'];
				}else{
					$list[$v['kuanhao']]['sum_2days'] = $v['2days'];
				}
				if(isset($list[$v['kuanhao']]['sum_3days'])){
					$list[$v['kuanhao']]['sum_3days'] += $v['3days'];
				}else{
					$list[$v['kuanhao']]['sum_3days'] = $v['3days'];
				}
				if(isset($list[$v['kuanhao']]['sum_7days'])){
					$list[$v['kuanhao']]['sum_7days'] += $v['7days'];
				}else{
					$list[$v['kuanhao']]['sum_7days'] = $v['7days'];
				}
				if(isset($list[$v['kuanhao']]['sum_30days'])){
					$list[$v['kuanhao']]['sum_30days'] += $v['30days'];
				}else{
					$list[$v['kuanhao']]['sum_30days'] = $v['30days'];
				}
				
				//根据其他属性2销量合计
				if(isset($other_2_sum[$v['other_2']]['1days'])){
					$other_2_sum[$v['other_2']]['1days'] += $v['1days'];
				}else{
					$other_2_sum[$v['other_2']]['1days'] = $v['1days'];
				}
				if(isset($other_2_sum[$v['other_2']]['2days'])){
					$other_2_sum[$v['other_2']]['2days'] += $v['2days'];
				}else{
					$other_2_sum[$v['other_2']]['2days'] = $v['2days'];
				}
				if(isset($other_2_sum[$v['other_2']]['3days'])){
					$other_2_sum[$v['other_2']]['3days'] += $v['3days'];
				}else{
					$other_2_sum[$v['other_2']]['3days'] = $v['3days'];
				}
				if(isset($other_2_sum[$v['other_2']]['7days'])){
					$other_2_sum[$v['other_2']]['7days'] += $v['7days'];
				}else{
					$other_2_sum[$v['other_2']]['7days'] = $v['7days'];
				}
				if(isset($other_2_sum[$v['other_2']]['30days'])){
					$other_2_sum[$v['other_2']]['30days'] += $v['30days'];
				}else{
					$other_2_sum[$v['other_2']]['30days'] = $v['30days'];
				}
				if(!isset($other_2_sum[$v['other_2']]['cycel'])){
					$other_2_sum[$v['other_2']]['cycel'] = $cycel_temp[$v['c_id']];
				}
				if(!isset($other_2_sum[$v['other_2']]['kuanhao'])){
					$other_2_sum[$v['other_2']]['kuanhao'] = $v['kuanhao'];
				}
				if(!isset($other_2_sum[$v['other_2']]['purchase_qty'])){
					$other_2_sum[$v['other_2']]['purchase_qty'] =  isset($kucun_temp[$v['other_2']]['purchase_qty'])?$kucun_temp[$v['other_2']]['purchase_qty']:0;
				}
				if(!isset($other_2_sum[$v['other_2']]['ys_qty'])){
					$other_2_sum[$v['other_2']]['ys_qty'] =  isset($kucun_temp[$v['other_2']]['qty'])?$kucun_temp[$v['other_2']]['qty']:0;
				}
				if($v['sales_add_time']){
					$other_2_sum[$v['other_2']]['sales_add_time'] = isset($other_2_sum[$v['other_2']]['sales_add_time']) ? $other_2_sum[$v['other_2']]['sales_add_time'] : 0;
					if($v['sales_add_time']>$other_2_sum[$v['other_2']]['sales_add_time']){
						$other_2_sum[$v['other_2']]['sales_add_time'] =   $v['sales_add_time'];
					}
				}
				if(!isset($other_2_sum[$v['other_2']]['cycel'])){
					$other_2_sum[$v['other_2']]['cycel'] =  $cycel_temp[$v['c_id']];;
				}
				if(!isset($other_2_sum[$v['other_2']]['name'])){
					$other_2_sum[$v['other_2']]['name'] =  $v['name'];;
				}

				
				//补货周期
				$list[$v['kuanhao']]['cycel'] = $cycel_temp[$v['c_id']];
				
				//品牌明细
				if($v['brand'] !='佑晟共享仓'){
					$list[$v['kuanhao']]['chima'][$v['other_2']]['brand_list'] = $brand_kuanhao_temp[$v['other_2']];
				}
				
				
				//款号+颜色+尺码明细
				$list[$v['kuanhao']]['chima'][$v['other_2']]['other_2'] = $v['other_2'];
				$list[$v['kuanhao']]['chima'][$v['other_2']]['purchase_qty'] = isset($kucun_temp[$v['other_2']]['purchase_qty'])?$kucun_temp[$v['other_2']]['purchase_qty']:0;
				$list[$v['kuanhao']]['chima'][$v['other_2']]['qty'] = isset($kucun_temp[$v['other_2']]['qty'])?$kucun_temp[$v['other_2']]['qty']:0;
			}	
		}
		//print_r($brand_kuanhao_temp);exit;
		//print_r($other_2_sum);exit;
		//计算补货
		if(isset($other_2_sum)){
			//建议生产数=7天销量/7*（生产周期+1天查货时间）-库存-生产中的库存
			//$shengchan_qty = 'round(s.7days/7*(c.cycel+1)-sum(i.qty)'.'-'.$production_qty.',0)';
			foreach($other_2_sum as $other_2 => &$other){
				$buhuo = round($other[$buhuo_by_days.'days']/$buhuo_by_days*($other['cycel']+1)-$other['ys_qty']-$other['purchase_qty'],0);
				$buhuo = $buhuo>0 ? $buhuo : 0;
				if(isset($list[$other['kuanhao']]['buhuo_total_qty'])){
					$list[$other['kuanhao']]['buhuo_total_qty'] += $buhuo;
				}else{
					$list[$other['kuanhao']]['buhuo_total_qty'] = $buhuo;
				}
				$list[$other['kuanhao']]['chima'][$other_2]['buhuo_qty'] = $buhuo;
				$other['buhuo_qty'] = $buhuo;
			}
		}
		//print_r($other_2_sum);exit;
		if(isset($list)){
			$list = $this->arraySort($list,$of,$or);
		}else{
			showmsg('暂无数据！', 'stop');
		}
		//print_r($other_2_sum);exit;
		if($download==0){
			include $this->admin_tpl('jst/jst_ys_dingzuo');
		}else{
			$excel = new xlswriter('ys_dingzuo',1,'款式汇总');
			//['other_2','1days','2days','3days','7days','30days','cycel','ys_qty','buhuo_qty','sales_add_time'];
			$data = [];
			foreach($list as $key => $val){
				$insert_data = [];
				$insert_data['other_2'] = $key;
				$insert_data['1days'] = $val['sum_1days'];
				$insert_data['2days'] = $val['sum_2days'];
				$insert_data['3days'] = $val['sum_3days'];
				$insert_data['7days'] = $val['sum_7days'];
				$insert_data['7days'] = $val['sum_7days'];
				$insert_data['30days'] = $val['sum_30days'];
				$insert_data['cycel'] = $val['cycel'];
				$insert_data['ys_qty'] = $val['total_qty'];
				$insert_data['buhuo_qty'] = $val['buhuo_total_qty'];
				$insert_data['ys_purchase_qty'] = $val['purchase_total_qty'];
				$insert_data['sales_add_time'] = $val['sales_add_time'];
				$insert_data['name'] = $val['name'];
				$data[] = $insert_data;
			}
			$excel->insert_data($data);
			$data = [];
			foreach($other_2_sum as $other_2=>$v){
				$insert_data = [];
				$insert_data = $v;
				$insert_data['other_2'] = $other_2;
				$insert_data['ys_purchase_qty'] = $v['purchase_qty'];
				//print_r($insert_data);exit;
				$data[] = $insert_data;
			}
			//print_r($data);exit;
			$excel->add_sheet('ys_dingzuo_total','款式尺码明细',$data);
			$excel->output();
		}
	}
	
	
	/*佑晟订做*/
	public function jeep_dingzuo(){
		$of = input('get.of');
		$or = input('get.or');
		$company='_jeep';
		$url = U('jeep_dingzuo');
		$of = in_array($of, array('other_2','sum_1days','sum_2days','sum_3days','sum_7days','sum_30days','total_qty','purchase_total_qty','buhuo_total_qty')) ? $of : 'sum_7days';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'DESC';
		$buhuo_by_days = isset($_GET['buhuo_by_days']) ? $_GET['buhuo_by_days'] : '3';
		$download = isset($_GET['download']) ? $_GET['download'] : 0;
		$where = '';
		if(isset($_GET['other_2'])&&trim($_GET['other_2'])){
			$where = ' and other_2 like "%'.trim($_GET['other_2']).'%"';
		}
		$where_name = '';
		if(isset($_GET['sku_name'])&&trim($_GET['sku_name'])){
			$where_name = ' and name like "%'.trim($_GET['sku_name']).'%"';
		}
		//订做商品库存列表
		$dingzuo_invertorys = D('jst_inventorys')->field('other_2,sum(qty) qty,substring_index(other_2,"#",1) kuanhao')->where('other_2 like "订做%"'.$where.' and brand in ("JEEP半成品","JEEP")')->group('other_2')->select();
		//采购商品库存，采用共享仓订做商品编码
		$dingzuo_purchase = D('jst_inventorys')->field('other_2,purchase_qty,sku_id,brand,substring_index(other_2,"#",1) kuanhao')->where('other_2 like "订做%" and purchase_qty>0 and brand="JEEP半成品"'.$where)->select();
		//print_r($dingzuo_invertorys);exit;
		$kucun_temp = [];
		if($dingzuo_purchase){
			foreach($dingzuo_purchase as $val){
				$other_2 = explode('#',$val['other_2']);
				//多个供应商商品编码不一致，需要累加
				if(isset($kucun_temp[$val['other_2']]['purchase_qty'])){
					$kucun_temp[$val['other_2']]['purchase_qty'] += $val['purchase_qty'];
				}else{
					$kucun_temp[$val['other_2']]['purchase_qty'] = $val['purchase_qty'];
				}
				
				if(isset($kucun_temp[$val['kuanhao']]['purchase_total_qty'])){
					$kucun_temp[$val['kuanhao']]['purchase_total_qty'] += $val['purchase_qty'];
				}else{
					$kucun_temp[$val['kuanhao']]['purchase_total_qty'] = $val['purchase_qty'];
				}
			}
		}
//print_r($kucun_temp);exit;
		if($dingzuo_invertorys){
			foreach($dingzuo_invertorys as $v){
				if(strpos($v['other_2'],'#')==false){
					exit('商品资料错误：'.$v['other_2']);
				}
				//$sku_name = md5(explode('#',$v['other_2'])[0]);
				//$properties_value = md5()
				if(isset($kucun_temp[$v['kuanhao']]['total_qty'])){
					$kucun_temp[$v['kuanhao']]['total_qty'] += $v['qty'];
				}else{
					$kucun_temp[$v['kuanhao']]['total_qty'] = $v['qty'];
				}
				$kucun_temp[$v['other_2']]['qty'] = $v['qty'];
			}
		}
		
		
		unset($dingzuo_invertorys);
		unset($dingzuo_purchase);
		
		//销售汇总根据店铺+款号
		$brand_kuanhao_list = D('jst_sku_sales')->alias('s')
			->field('s.other_2,sum(s.1days) sum_1days,sum(s.2days) sum_2days,sum(s.3days) sum_3days,sum(s.7days) sum_7days,sum(s.30days) sum_30days,substring_index(s.other_2,"#",1) kuanhao,CONCAT(s.brand,s.other_2) brand_kuanhao,s.brand')
			->where("s.other_2 like '订做%' and s.brand in ('JEEP半成品','JEEP') and s.enabled = 1 ".$where)
			->group('CONCAT(s.brand,s.other_2)')
			->select();
			
		
		//所有定制商品列表
		$all_list = D('jst_sku_sales')->alias('s')
			->field('s.other_2,s.1days,s.2days,s.3days,s.7days,s.30days,substring_index(s.other_2,"#",1) kuanhao,s.brand,s.pic,s.c_id,s.sales_add_time,name')
			->where("s.other_2 like '订做%' and s.brand in ('JEEP半成品','JEEP')".$where.$where_name)
			->select();

		//补货周期
		$category_list = D('jst_category')->field('c_id,cycel')->select();
		$cycel_temp = [];
		foreach($category_list as $category){
			$cycel_temp[$category['c_id']] = $category['cycel'];
		}
			
		if($brand_kuanhao_list){
			$brand_kuanhao_temp = [];
			foreach($brand_kuanhao_list as $k=>$brand_kuanhao){
				if($brand_kuanhao['brand'] == 'JEEP半成品'){
					continue;
				}
				$brand_kuanhao_temp[$brand_kuanhao['other_2']][$brand_kuanhao['brand']] = $brand_kuanhao;
			}
		}
//print_r($all_list);exit;
		if($all_list){
			$list = [];
			$other_2_sum = [];
			foreach($all_list as $v){
				/*款号统计资料*/
				//图片
				$list[$v['kuanhao']]['pic'] = $v['pic'];
				$list[$v['kuanhao']]['name'] = $v['name'];
				if(!isset($list[$v['kuanhao']]['sales_add_time'])&&$v['sales_add_time']){
					$list[$v['kuanhao']]['sales_add_time'] = $v['sales_add_time'];
				}
				if($v['sales_add_time']){
					$list[$v['kuanhao']]['sales_add_time'] = isset($list[$v['kuanhao']]['sales_add_time']) ? $list[$v['kuanhao']]['sales_add_time'] : 0;
					if($v['sales_add_time']>$list[$v['kuanhao']]['sales_add_time']){
						$list[$v['kuanhao']]['sales_add_time'] =   $v['sales_add_time'];
					}
				}
				
				//款号库存总和
				if(!isset($list[$v['kuanhao']]['kucun'])){
					$list[$v['kuanhao']]['total_qty'] = isset($kucun_temp[$v['kuanhao']]['total_qty'])?$kucun_temp[$v['kuanhao']]['total_qty']:0;
				}
				//款号生产中的库存总和
				if(!isset($list[$v['kuanhao']]['purchase_total_qty'])){
					$list[$v['kuanhao']]['purchase_total_qty'] = isset($kucun_temp[$v['kuanhao']]['purchase_total_qty'])?$kucun_temp[$v['kuanhao']]['purchase_total_qty']:0;
				}
				//款号销量合计
				if(isset($list[$v['kuanhao']]['sum_1days'])){
					$list[$v['kuanhao']]['sum_1days'] += $v['1days'];
				}else{
					$list[$v['kuanhao']]['sum_1days'] = $v['1days'];
				}
				if(isset($list[$v['kuanhao']]['sum_2days'])){
					$list[$v['kuanhao']]['sum_2days'] += $v['2days'];
				}else{
					$list[$v['kuanhao']]['sum_2days'] = $v['2days'];
				}
				if(isset($list[$v['kuanhao']]['sum_3days'])){
					$list[$v['kuanhao']]['sum_3days'] += $v['3days'];
				}else{
					$list[$v['kuanhao']]['sum_3days'] = $v['3days'];
				}
				if(isset($list[$v['kuanhao']]['sum_7days'])){
					$list[$v['kuanhao']]['sum_7days'] += $v['7days'];
				}else{
					$list[$v['kuanhao']]['sum_7days'] = $v['7days'];
				}
				if(isset($list[$v['kuanhao']]['sum_30days'])){
					$list[$v['kuanhao']]['sum_30days'] += $v['30days'];
				}else{
					$list[$v['kuanhao']]['sum_30days'] = $v['30days'];
				}
				
				//根据其他属性2销量合计
				if(isset($other_2_sum[$v['other_2']]['1days'])){
					$other_2_sum[$v['other_2']]['1days'] += $v['1days'];
				}else{
					$other_2_sum[$v['other_2']]['1days'] = $v['1days'];
				}
				if(isset($other_2_sum[$v['other_2']]['2days'])){
					$other_2_sum[$v['other_2']]['2days'] += $v['2days'];
				}else{
					$other_2_sum[$v['other_2']]['2days'] = $v['2days'];
				}
				if(isset($other_2_sum[$v['other_2']]['3days'])){
					$other_2_sum[$v['other_2']]['3days'] += $v['3days'];
				}else{
					$other_2_sum[$v['other_2']]['3days'] = $v['3days'];
				}
				if(isset($other_2_sum[$v['other_2']]['7days'])){
					$other_2_sum[$v['other_2']]['7days'] += $v['7days'];
				}else{
					$other_2_sum[$v['other_2']]['7days'] = $v['7days'];
				}
				if(isset($other_2_sum[$v['other_2']]['30days'])){
					$other_2_sum[$v['other_2']]['30days'] += $v['30days'];
				}else{
					$other_2_sum[$v['other_2']]['30days'] = $v['30days'];
				}
				if(!isset($other_2_sum[$v['other_2']]['cycel'])){
					$other_2_sum[$v['other_2']]['cycel'] = $cycel_temp[$v['c_id']];
				}
				if(!isset($other_2_sum[$v['other_2']]['kuanhao'])){
					$other_2_sum[$v['other_2']]['kuanhao'] = $v['kuanhao'];
				}
				if(!isset($other_2_sum[$v['other_2']]['purchase_qty'])){
					$other_2_sum[$v['other_2']]['purchase_qty'] =  isset($kucun_temp[$v['other_2']]['purchase_qty'])?$kucun_temp[$v['other_2']]['purchase_qty']:0;
				}
				if(!isset($other_2_sum[$v['other_2']]['ys_qty'])){
					$other_2_sum[$v['other_2']]['ys_qty'] =  isset($kucun_temp[$v['other_2']]['qty'])?$kucun_temp[$v['other_2']]['qty']:0;
				}
				if($v['sales_add_time']){
					$other_2_sum[$v['other_2']]['sales_add_time'] = isset($other_2_sum[$v['other_2']]['sales_add_time']) ? $other_2_sum[$v['other_2']]['sales_add_time'] : 0;
					if($v['sales_add_time']>$other_2_sum[$v['other_2']]['sales_add_time']){
						$other_2_sum[$v['other_2']]['sales_add_time'] =   $v['sales_add_time'];
					}
				}
				if(!isset($other_2_sum[$v['other_2']]['cycel'])){
					$other_2_sum[$v['other_2']]['cycel'] =  $cycel_temp[$v['c_id']];;
				}
				if(!isset($other_2_sum[$v['other_2']]['name'])){
					$other_2_sum[$v['other_2']]['name'] =  $v['name'];;
				}

				
				//补货周期
				$list[$v['kuanhao']]['cycel'] = $cycel_temp[$v['c_id']];
				
				//品牌明细
				if($v['brand'] !='JEEP半成品'){
					$list[$v['kuanhao']]['chima'][$v['other_2']]['brand_list'] = $brand_kuanhao_temp[$v['other_2']];
				}
				
				
				//款号+颜色+尺码明细
				$list[$v['kuanhao']]['chima'][$v['other_2']]['other_2'] = $v['other_2'];
				$list[$v['kuanhao']]['chima'][$v['other_2']]['purchase_qty'] = isset($kucun_temp[$v['other_2']]['purchase_qty'])?$kucun_temp[$v['other_2']]['purchase_qty']:0;
				$list[$v['kuanhao']]['chima'][$v['other_2']]['qty'] = isset($kucun_temp[$v['other_2']]['qty'])?$kucun_temp[$v['other_2']]['qty']:0;
			}	
		}
		//print_r($brand_kuanhao_temp);exit;
		//print_r($other_2_sum);exit;
		//计算补货
		if(isset($other_2_sum)){
			//建议生产数=7天销量/7*（生产周期+1天查货时间）-库存-生产中的库存
			//$shengchan_qty = 'round(s.7days/7*(c.cycel+1)-sum(i.qty)'.'-'.$production_qty.',0)';
			foreach($other_2_sum as $other_2 => &$other){
				$buhuo = round($other[$buhuo_by_days.'days']/$buhuo_by_days*($other['cycel']+1)-$other['ys_qty']-$other['purchase_qty'],0);
				$buhuo = $buhuo>0 ? $buhuo : 0;
				if(isset($list[$other['kuanhao']]['buhuo_total_qty'])){
					$list[$other['kuanhao']]['buhuo_total_qty'] += $buhuo;
				}else{
					$list[$other['kuanhao']]['buhuo_total_qty'] = $buhuo;
				}
				$list[$other['kuanhao']]['chima'][$other_2]['buhuo_qty'] = $buhuo;
				$other['buhuo_qty'] = $buhuo;
			}
		}
		//print_r($other_2_sum);exit;
		if(isset($list)){
			$list = $this->arraySort($list,$of,$or);
		}else{
			showmsg('暂无数据！', 'stop');
		}
		//print_r($other_2_sum);exit;
		if($download==0){
			include $this->admin_tpl('jst/jst_ys_dingzuo');
		}else{
			$excel = new xlswriter('ys_dingzuo',1,'jeep款式汇总');
			//['other_2','1days','2days','3days','7days','30days','cycel','ys_qty','buhuo_qty','sales_add_time'];
			$data = [];
			foreach($list as $key => $val){
				$insert_data = [];
				$insert_data['other_2'] = $key;
				$insert_data['1days'] = $val['sum_1days'];
				$insert_data['2days'] = $val['sum_2days'];
				$insert_data['3days'] = $val['sum_3days'];
				$insert_data['7days'] = $val['sum_7days'];
				$insert_data['7days'] = $val['sum_7days'];
				$insert_data['30days'] = $val['sum_30days'];
				$insert_data['cycel'] = $val['cycel'];
				$insert_data['ys_qty'] = $val['total_qty'];
				$insert_data['buhuo_qty'] = $val['buhuo_total_qty'];
				$insert_data['ys_purchase_qty'] = $val['purchase_total_qty'];
				$insert_data['sales_add_time'] = $val['sales_add_time'];
				$insert_data['name'] = $val['name'];
				$data[] = $insert_data;
			}
			$excel->insert_data($data);
			$data = [];
			foreach($other_2_sum as $other_2=>$v){
				$insert_data = [];
				$insert_data = $v;
				$insert_data['other_2'] = $other_2;
				$insert_data['ys_purchase_qty'] = $v['purchase_qty'];
				//print_r($insert_data);exit;
				$data[] = $insert_data;
			}
			//print_r($data);exit;
			$excel->add_sheet('ys_dingzuo_total','jeep款式尺码明细',$data);
			$excel->output();
		}
	}
	
	
	
	/*唯品补货*/
	public function wp_buhuo(){
		$type = isset($_GET['type']) ? $_GET['type'] : '';
		if($type == 'touwei'){//头尾码设置列表
			$data = D('jst_sku_touwei')->order('chima_num asc')->select();
			$tou = $data[0];
			$wei = end($data);
			array_unshift($data,['chima_num'=>'<'.$tou['chima_num'],'tou_num'=>0,'wei_num'=>0,'remark'=>'均码不设置头尾码']);
			$data[] = ['chima_num'=>'>'.$wei['chima_num'],'tou_num'=>2,'wei_num'=>2,'remark'=>'尺码多头尾个2个尺码'];
			include $this->admin_tpl('jst/jst_wp_buhuo_touwei');
			return;
		}else if($type == 'reset_touwei'){//重置头尾码
			delcache('LOCK::get_touwei');
			if(isset($_GET['error'])){
				$res = D('jst_sku')->update(['tou_wei'=>0],['tou_wei'=>-1]);
				if($res !== false){
					return_json(array('status'=>1,'message'=>'操作成功，将在后台执行重新计算异常头尾码'));
				}else{
					return_json(array('status'=>0,'message'=>L('operation_failure')));
				}	
			}else{
				$res = D('jst_sku')->update(['tou_wei'=>0],'1');
				if($res !== false){
					return_json(array('status'=>1,'message'=>'操作成功，将在后台执行重新计算头尾码,预计需要30分钟'));
				}else{
					return_json(array('status'=>0,'message'=>L('operation_failure')));
				}	
			}
		}else if($type == 'tag'){//标签列表
			$brand = isset($_GET['brand']) ? $_GET['brand'] : '';
			$where = [];
			if($brand){
				$where = "brand in ('全局','".$brand."')";
			}else{
				$where = "brand in ('全局','默认')";
			}
			$data = D('jst_sku_tag')->order('id asc')->where($where)->select();
			if(!$brand){
				include $this->admin_tpl('jst/jst_wp_buhuo_tag');
				return;
			}
			$info =  D('jst_sku_tag')->order('id asc')->where(['brand'=>$brand])->select();
			if(!$info){
				$data = D('jst_sku_tag')->order('id asc')->where(['brand'=>'默认'])->select();
				foreach($data as $v){
					$v['brand'] = $brand;
					unset($v['id']);
					$insert_data[] = $v;
				}
				D('jst_sku_tag')->insert_all($insert_data);
				$data = D('jst_sku_tag')->order('id asc')->where($where)->select();
			}
			delcache('CONFIG::BUHUO:*');
			return_json(array('status'=>1,'data'=>$data));
		}else if($type == "tag_add"){//添加标签
			if(isset($_GET['dosubmit'])){
				$_GET["brand"] = str_replace('+',' ',$_GET["brand"]);
				$res = D('jst_sku_tag')->insert($_GET);
				if($res !== false){
					return_json(array('status'=>1,'message'=>L('operation_success')));
				}else{
					return_json(array('status'=>0,'message'=>L('operation_failure')));
				}
			}
			$info = ['tag_name'=>'','days_avg'=>'','id'=>'','days_num'=>'','remark'=>''];
			include $this->admin_tpl('jst/jst_wp_buhuo_tag_add');
			return;
		}else if($type == "tag_edit"){//编辑标签
			$id = $_GET['id'];
			if(isset($_GET['dosubmit'])){
				$_GET["brand"] = str_replace('+',' ',$_GET["brand"]);
				$res = D('jst_sku_tag')->update($_GET,['id'=>$id]);
				delete_all('CONFIG::BUHUO*');
				if($res !== false){
					return_json(array('status'=>1,'message'=>L('operation_success')));
				}else{
					return_json(array('status'=>0,'message'=>L('operation_failure')));
				}
			}
			$info = D('jst_sku_tag')->where(['id'=>$id])->find();
			include $this->admin_tpl('jst/jst_wp_buhuo_tag_add');
			return;
		}else if($type == "tag_del"){//删除标签
			$res = D('jst_sku_tag')->delete(['id'=>$_GET['id']]);
			delete_all('CONFIG::BUHUO*');
			if($res !== false){
				return_json(array('status'=>1,'message'=>L('operation_success')));
			}else{
				return_json(array('status'=>0,'message'=>L('operation_failure')));
			}
		}else if($type == "add_remark"){//添加补货备注
			$kuan = $_GET['kuan'];
			$info = D('jst_buhuo_remark')->field('*')->where(['kuan'=>$kuan])->find();
			if(!$info){
				$info['kuan'] = $_GET['kuan'];
				$info['remark'] = '';
				$info['id'] = '';
			}
			include $this->admin_tpl('jst/jst_wp_buhuo_remark');
			exit;
		}else if($type == 'action_remark'){//提交补货备注
			$id = isset($_GET['id'])?$_GET['id']:0;
			//去除所有空白字符
			$remark = preg_replace("/\s|　/","",$_GET['remark']);
			$kuan = $_GET['kuan'];
			if($id){
				$res = D('jst_buhuo_remark')->update($_GET,['id'=>$id]);
			}else{
				$res = D('jst_buhuo_remark')->insert($_GET);
			}
			if($res){
				return_json(array('status'=>1,'message'=>'操作成功'));
			}else{
				return_json(array('status'=>0,'message'=>'添加失败'));
			}
		}else if($type == 'del_remark'){//删除补货备注
			if(D('jst_buhuo_remark')->delete(['id'=>$_GET['id']])){
				return_json(array('status'=>1,'message'=>'删除成功'));
			}else{
				return_json(array('status'=>0,'message'=>'删除失败'));
			}
		}
		
		
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('s.id','s.sku_id','s.i_id','s.enabled','s.modified','s.created','s.add_time','sum_1days','sum_2days','sum_3days','sum_7days','sum_30days')) ? $of : 's.id';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'ASC';
		$enabled = isset($_GET["enabled"]) ? $_GET["enabled"] : 1;
		$brand = isset($_GET["brand"]) ? $_GET["brand"] : '法派FAPAI';
		$labels_brand = isset($_GET['labels_brand']) ? $_GET['labels_brand'] : '';
		$labels = isset($_GET['labels']) ? $_GET['labels'] : '';
		$download = isset($_GET['download']) ? $_GET['download'] : 0;

		$sku = D('jst_sku_sales');
		if($brand){
			$brand = str_replace('+',' ',$brand);
		}
		
		$where = '1=1';
		if(isset($_GET['dosubmit'])){	
			$i_id = isset($_GET["i_id"]) ? $_GET["i_id"] : '';
			$tou_wei = isset($_GET["tou_wei"]) ? $_GET["tou_wei"] : '';
			$sku_id = isset($_GET["sku_id"]) ? $_GET["sku_id"] : '';
			$sku_code = isset($_GET["sku_code"]) ? $_GET["sku_code"] : '';
			$other_2 = isset($_GET["other_2"]) ? trim($_GET["other_2"]) : '';
			$properties_value = isset($_GET['properties_value']) ? safe_replace(trim($_GET['properties_value'])) : '';
			$name = isset($_GET["name"]) ? trim($_GET["name"]) : '';
			
			$c_id = isset($_GET["c_id"]) ? $_GET["c_id"] : '';
			if($i_id) {
				if(strpos($i_id,'*') !== false){
					$i_id = trim($i_id,'*');
					$where .= ' AND i_id LIKE \'%'.$i_id.'%\'';
				}else{
					$where .= ' AND i_id = "'.$i_id.'"';
				}
			}
			if($sku_id) {
				if(strpos($sku_id,'*') !== false){
					$sku_id = trim($sku_id,'*');
					$where .= ' AND sku_id LIKE \'%'.$sku_id.'%\'';
				}else{
					$where .= ' AND sku_id = "'.$sku_id.'"';
				}
			}
			if($sku_code) {
				$where .= ' AND sku_code = "'.$sku_code.'"';
			}
			if($other_2){
				$where .=' AND other_2 LIKE \'%'.$other_2.'%\'';
			}
			if($properties_value) {
				$where .= ' AND properties_value LIKE \'%'.$properties_value.'%\'';
			}
			if($name) {
				$where .= ' AND name LIKE \'%'.$name.'%\'';
			}
			if($c_id) {
				$where .= ' AND c_id ='.$c_id;
			}
			if($tou_wei!=''){
				$tou_wei_arr = explode(',',$tou_wei);
				$tou_wei_arr = implode('","',$tou_wei_arr);
				$where .= ' AND tou_wei in ("'.$tou_wei_arr.'")';
			}
			if($labels_brand){
				$labels_brand_arr = explode(',',$labels_brand);
				$labels_brand_arr = implode('","',$labels_brand_arr);
				$where .= ' AND labels_brand in ("'.$labels_brand_arr.'")';
			}
			if($labels){
				$labels_arr = explode(',',$labels);
				foreach($labels_arr as $label){
					$where .= ' AND labels like "%'.$label.'%"';
				}
			}
		}
		if(isset($enabled)) {
			if($enabled != 99){
				$where .= ' AND enabled = '.$enabled;
			}
		}
		
		if($brand) {
			$brand_arr = explode(',',$brand);
			$brand_arr = implode('","',$brand_arr);
			$where .= ' AND brand in ("'.$brand_arr.'")';
		}else{
			$str = [];
			foreach(brand_names() as $v){
				if(in_array($v,['佑晟共享仓','天钧新塘仓','JEEP半成品','马克华菲半成品'])){
					continue;
				}
				$str[] = '"'.$v.'"';
			}
			$where .= ' AND brand in('.implode($str,',').')';
		}
		
		$total = $sku->field('count(distinct CONCAT(i_id,substring_index(properties_value,";",1))) count')->where($where)->find();
		$total = $total['count'];
		if($download==0){
			$page = new page($total, 100);
			$data = $sku->alias('s')->field('s.i_id,s.pic,s.name,s.brand,s.category,substring_index(s.properties_value,";",1) color,s.labels,s.labels_brand,sum(s.1days) sum_1days,sum(s.2days) sum_2days,sum(s.3days) sum_3days,sum(s.5days) sum_5days,sum(s.7days) sum_7days,s.enabled,s.created,s.modified,r.remark')->join('yzm_jst_buhuo_remark r on r.kuan=concat(s.i_id,substring_index(properties_value,";",1))','left')->where($where)->limit($page->limit())->order("$of $or")->group('CONCAT(i_id,substring_index(properties_value,";",1))')->select();
			//print_r($data);exit;
			if($data){
				foreach($data as &$d){
					//趋势
					$d['trend'] = avg_trend($d['sum_3days']/3,$d['sum_7days']/7);
					$d['qty'] = 0;
					$d['beihuo_qty'] = 0;
					$d['buhuo_qty'] = 0;
					$d['virtual_qty'] = 0;
					//日均
					$d['d'] = 0;
					//是否有备货仓
					$d['is_beihuo'] = 0;
					$brand_beihuo = brand_beihuo($d['brand'],$d['labels_brand']);
					$d['days_num'] = $brand_beihuo['days_num'];
					$d['days'] = $brand_beihuo['days'];
					//$d['days_num'] = brand_beihuo($d['brand'],$d['labels_brand']);
					$d['sku_list'] = $sku->alias('s')
						->field('s.*,i.qty,i.virtual_qty')				
						->join('yzmcms_jst_inventorys i ON i.sku_id=s.sku_id', 'left')
						->where(['s.i_id'=>$d['i_id'],'substring_index(properties_value,";",1)'=>$d['color']])->order("s.other_2 asc,s.name asc")->select();
						
					foreach($d['sku_list'] as &$sl){
						$sl['d'] = 0;
						if(isset($sl[$d['days'].'days'])){
							$sl['d'] = round($sl[$d['days'].'days']/$d['days']);
						}
						$sl['beihuo_qty'] = 0;
						$d['d'] += $sl['d'];
						$d['qty'] += $sl['qty'];
						$d['virtual_qty'] += $sl['virtual_qty'];
						if(strpos($sl['labels'],'备货仓')>-1){
							if($d['brand']=='JEEP'){
								$sl['beihuo_qty'] = D('jst_inventorys')->field('sum(qty)')->where(['other_2'=>$sl['other_2'],'brand'=>'JEEP半成品'])->one();
							}elseif($d['brand']!='法派FAPAI'){
								$sl['beihuo_qty'] = D('jst_inventorys')->field('sum(qty)')->where(['other_2'=>$sl['other_2'],'brand'=>'佑晟共享仓'])->one();
							}else{
								$sl['beihuo_qty'] = D('jst_inventorys')->field('sum(in_qty)')->where(['other_2'=>$sl['other_2']])->one();
							}
							$d['beihuo_qty'] += $sl['beihuo_qty'];
							$d['is_beihuo'] = 1;
						}
						//补货数量
						$sl['buhuo_qty'] = 0;
						if($d['days_num']>0){
							$need_buhuo = $sl['d']*$d['days_num'];
							//小销量款-，默认不补货
							if($sl['labels_brand'] == '小销量-'){
								$need_buhuo = 0;
							}else if($sl['labels_brand'] == '小销量+'){
								//小销量款+，头尾不补货
								if(in_array($sl['tou_wei'],[1,3])){
									$need_buhuo = 0;
								}else if($need_buhuo<3){
									//非头尾码至少需要补货到3件
									$need_buhuo = 3;
								}
							}else{
								if(in_array($sl['tou_wei'],[1,3])&&$need_buhuo<3){
									//头尾码至少需要补货到3件
									$need_buhuo = 3;
								}
							}
							$buhuo_qty = $need_buhuo-$sl['qty'];
							//补货1件时不补货
							if($buhuo_qty<2){
								$buhuo_qty = 0;
								continue;
							}
							//需要补两件是按3件补
							if($buhuo_qty == 2 || $buhuo_qty == 3){
								$sl['buhuo_qty'] = 3;
							}else{
								//库存大于8件，补货数量小于3件，无需补货
								if($sl['qty']>7&&$buhuo_qty<3){
									$sl['buhuo_qty'] = 0;
								}else{
									$sl['buhuo_qty'] = round($buhuo_qty/5)*5;
								}
							}
						}
						$d['buhuo_qty'] += $sl['buhuo_qty'];
					}
						
				}
			}
			include $this->admin_tpl('jst/jst_wp_buhuo');
		}else{
			$number = 50000;
			$page = ceil($total/$number);
			$excel = new xlswriter('wp_buhuo',1);
			$excel->page();
			for($i=1;$i<=$page;$i++){
				//插入excel的数据
				$excel_data = [];
				$limit = ($i-1)*$number.','.$number;
				$data = $sku->alias('s')->field('i_id,pic,name,brand,category,substring_index(properties_value,";",1) color,labels,labels_brand,sum(1days) sum_1days,sum(2days) sum_2days,sum(3days) sum_3days,sum(5days) sum_5days,sum(7days) sum_7days,round(if((sum(3days/3)-sum(7days/7))/sum(3days/3)>=0.1,sum(3days/3),sum(7days/7)),0) as d,enabled,created,modified,r.remark')->join('yzm_jst_buhuo_remark r on r.kuan=concat(s.i_id,substring_index(properties_value,";",1))','left')->where($where)->limit($limit)->order("$of $or")->group('CONCAT(i_id,substring_index(properties_value,";",1))')->select();
				//print_r($data);exit;
				$field = 's.i_id,s.sku_id,s.properties_value,s.name,s.other_2,s.brand,s.labels,s.labels_brand,i.qty,i.virtual_qty,s.1days,s.2days,s.3days,s.5days,s.7days,s.tou_wei';
				if($data){
					foreach($data as $d){
						//趋势
						$d['trend'] = avg_trend($d['sum_3days']/3,$d['sum_7days']/7);
						//日均
						$d['d'] = 0;
						$brand_beihuo = brand_beihuo($d['brand'],$d['labels_brand']);
						$d['days_num'] = $brand_beihuo['days_num'];
						$d['days'] = $brand_beihuo['days'];
						$sku_list = $sku->alias('s')
							->field($field)				
							->join('yzmcms_jst_inventorys i ON i.sku_id=s.sku_id', 'left')
							->where(['s.i_id'=>$d['i_id'],'substring_index(properties_value,";",1)'=>$d['color']])->order("s.other_2 asc,s.name asc")->select();
							//print_r($sku_list);
						foreach($sku_list as $sl){
							//备注
							$sl['remark'] = $d['remark']??'';
							$sl['d'] = 0;
							if(isset($sl[$d['days'].'days'])){
								$sl['d'] = round($sl[$d['days'].'days']/$d['days']);
							}
							$sl['beihuo_qty'] = 0;
							if(strpos($sl['labels'],'备货仓')){
								if($d['brand']!='法派FAPAI'){
									$sl['beihuo_qty'] = D('jst_inventorys')->field('sum(qty)')->where(['other_2'=>$sl['other_2']])->one();
								}else{
									$sl['beihuo_qty'] = D('jst_inventorys')->field('sum(in_qty)')->where(['other_2'=>$sl['other_2']])->one();
								}
							}
							$sl['i_id'] .= '('.$d['color'].')';
							$sl['labels'] = trim($sl['labels'].','.touwei_code($sl['tou_wei']),',');
							//备货天数
							$sl['days_num'] = $d['days_num'];
							$d['d'] += $sl['d'];
							$sl['trend'] = $d['trend'];
							//补货数量
							$sl['buhuo_qty'] = 0;
							if($d['days_num']>0){
								$need_buhuo = $sl['d']*$d['days_num'];
								//小销量款-，默认不补货
								if($sl['labels_brand'] == '小销量-'){
									$need_buhuo = 0;
								}else if($sl['labels_brand'] == '小销量+'){
									//小销量款+，头尾不补货
									if(in_array($sl['tou_wei'],[1,3])){
										$need_buhuo = 0;
									}else if($need_buhuo<3){
										//非头尾码至少需要补货到3件
										$need_buhuo = 3;
									}
								}else{
									if(in_array($sl['tou_wei'],[1,3])&&$need_buhuo<3){
										//头尾码至少需要补货到3件
										$need_buhuo = 3;
									}
								}
								$buhuo_qty = $need_buhuo-$sl['qty'];
								//补货1件时不补货
								if($buhuo_qty<2){
									$buhuo_qty = 0;
									$sl['buhuo_qty'] = 0;
								}else{
									//无需补货
									if($buhuo_qty==1){
										$sl['buhuo_qty'] = 0;
									}else{
										//需要补两件是按3件补
										if($buhuo_qty == 2 || $buhuo_qty == 3){
											$sl['buhuo_qty'] = 3;
										}else{
											//库存大于8件，补货数量小于3件，无需补货
											if($sl['qty']>7&&$buhuo_qty<3){
												$sl['buhuo_qty'] = 0;
											}else if($sl['qty']>20&&$buhuo_qty<5){
												//库存大于15件，补货数量小于5件，无需补货
												$sl['buhuo_qty'] = 0;
											}else{
												$sl['buhuo_qty'] = round($buhuo_qty/5)*5;
											}
										}
									}
								}
							}
							$excel_data[] = $sl;
						}
					}
					//print_r($excel_data);exit;
				}
				$excel->insert_data($excel_data);
				unset($excel_data);
			}
			$excel->output();	
		}
	}
	
	//统计
	public function trend(){
		$type = isset($_GET['type']) ? $_GET['type'] : '';
		$kuan = isset($_GET['kuan']) ? $_GET['kuan'] : '';
		if(!$kuan || !$type){
			exit('参数错误！');
		}
		$days = isset($_GET['days']) ? $_GET['days'] : 7;
		$end = strtotime(date('Y-m-d',time()));
		$start = $end - 86400*$days;
		if($type == 'i_id'){
			$list = D('jst_orders_items')->field("FROM_UNIXTIME(order_date, '%m-%d') date, sum( qty ) qty, order_date, CONCAT(i_id,substring_index(properties_value,';',1))")->where("CONCAT(i_id,substring_index(properties_value,';',1)) = '".$kuan."' AND status_code in (2,4,7,8,9) AND order_date>".$start)->limit($days)->order("order_date ASC")->group("FROM_UNIXTIME(order_date,'%Y-%m-%d')")->select();
		}else if($type == 'other_2'){
			$list = D('jst_sku')->alias('s')
				->field("FROM_UNIXTIME(oi.order_date,'%m-%d') date,sum(oi.qty) qty,substring_index(s.other_2,'#',1) kuanhao")
				->join('yzmcms_jst_orders_items oi ON oi.sku_id=s.sku_id', 'left')
				->where("s.brand in ('东方骆驼','增致牛仔 ZENGZHI','米菲 MIFFY','雅鹿','琴曼','GOOGIMS','ICE','安瑞井','MOYO','美丽衣橱','JEEP') and substring_index(s.other_2,'#',1) = '".$kuan."' AND status_code in (2,4,7,8,9) AND order_date>".$start)
				->limit($days)
				->order("oi.order_date ASC")
				->group("FROM_UNIXTIME(oi.order_date,'%Y-%m-%d')")
				->select();
		}

		$data = [];
		$dates = [];
		for($i=$days;$i>0;$i--){
			$date = date('m-d',$end-86400*$i);
			$data[$date] = 0;
			$dates[] = $date; 
		}
		foreach($list as $v){
			if(in_array($v['date'],$dates)){
				$data[$v['date']] = $v['qty'];
			}
		}
		$qty = json_encode(array_values($data));
		$data = json_encode(array_keys($data));
		
		include $this->admin_tpl('jst/jst_trend');
		return;	
	}
	
	//异常库存
	public function error_inventorys(){
		
		/*备注增、删、改*/
		$type = $_GET['type']??'';
		if($type == "add_remark"){//添加补货备注
			$other_2 = $_GET['other_2'];
			$info = D('jst_inventorys_remark')->field('*')->where(['other_2'=>$other_2])->find();
			if(!$info){
				$info['other_2'] = $_GET['other_2'];
				$info['remark'] = '';
				$info['id'] = '';
			}
			include $this->admin_tpl('jst/jst_inventorys_remark');
			exit;
		}else if($type == 'action_remark'){//提交补货备注
			$id = isset($_GET['id'])?$_GET['id']:0;
			//去除所有空白字符
			$remark = preg_replace("/\s|　/","",$_GET['remark']);
			if($id){
				$res = D('jst_inventorys_remark')->update($_GET,['id'=>$id]);
			}else{
				$res = D('jst_inventorys_remark')->insert($_GET);
			}
			if($res){
				return_json(array('status'=>1,'message'=>'操作成功'));
			}else{
				return_json(array('status'=>0,'message'=>'添加失败'));
			}
		}else if($type == 'del_remark'){//删除补货备注
			if(D('jst_inventorys_remark')->delete(['id'=>$_GET['id']])){
				return_json(array('status'=>1,'message'=>'删除成功'));
			}else{
				return_json(array('status'=>0,'message'=>'删除失败'));
			}
		}
		
		
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('i.id','sum_qty','sum_virtual_qty','sum_purchase_qty','sum_return_qty','sum_in_qty','sum_pick_lock','sum_order_lock','sum_defective_qty','i.other_2')) ? $of : 'i.other_2';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'ASC';
		$inventorys = D('jst_inventorys');
		$download = isset($_GET['download']) ? $_GET['download'] : 0;
		$where = '1=1';
		$having = '1=1';
		$is_remark = $_GET['is_remark'] ?? 0;
		$brand = isset($_GET["brand"]) ? $_GET["brand"] : '';
		$brand_list = ['佑晟共享仓','增致牛仔 ZENGZHI','东方骆驼','米菲 MIFFY','雅鹿','法派FAPAI','安瑞井','MOYO','琴曼','美丽衣橱','GOOGIMS','ICE'];
		if(isset($_GET['dosubmit'])){	
			$i_id = isset($_GET["i_id"]) ? $_GET["i_id"] : '';
			$sku_id = isset($_GET["sku_id"]) ? $_GET["sku_id"] : '';
			$sku_code = isset($_GET["sku_code"]) ? $_GET["sku_code"] : '';
			$properties_value = isset($_GET['properties_value']) ? safe_replace(trim($_GET['properties_value'])) : '';
			$sku_name = isset($_GET["name"]) ? $_GET["name"] : '';
			$other_2 = isset($_GET["other_2"]) ? $_GET["other_2"] : '';
			$error_type = isset($_GET["error_type"]) ? $_GET["error_type"] : '';
			$qty_lt = $_GET['qty_lt']??'';
			$qty_gt = $_GET['qty_gt']??'';
			if($brand){
				$brand = str_replace('+',' ',$brand);
			}
		
			if($i_id) {
				if(strpos($i_id,'*') !== false){
					$i_id = trim($i_id,'*');
					$where .= ' AND i.i_id LIKE \'%'.$i_id.'%\'';
				}else{
					$where .= ' AND i.i_id = "'.$i_id.'"';
				}
			}
			if($sku_id) {
				if(strpos($sku_id,'*') !== false){
					$sku_id = trim($sku_id,'*');
					$where .= ' AND i.sku_id LIKE \'%'.$sku_id.'%\'';
				}else{
					$where .= ' AND i.sku_id = "'.$sku_id.'"';
				}
			}
			if($sku_code) {
				$where .= ' AND i.sku_code = "'.$sku_code.'"';
			}
			if($properties_value) {
				$where .= ' AND i.properties_value LIKE \'%'.$properties_value.'%\'';
			}
			if($sku_name) {
				$where .= ' AND i.sku_name LIKE \'%'.$sku_name.'%\'';
			}
			if($other_2) {
				$where .= ' AND i.other_2 LIKE \'%'.$other_2.'%\'';
			}
			if($error_type) {
				$error_type_arr = explode(',',$error_type);
				$error_type_arr = implode('","',$error_type_arr);
				$where .= ' AND i.error_type in ("'.$error_type_arr.'")';
			}
			if($qty_gt){
				$having .=' AND (sum_qty+sum_in_qty)<'.$qty_gt;
			}
			if($qty_lt){
				$having .=' AND (sum_qty+sum_in_qty)>'.$qty_lt;
			}
		}
		if($brand) {
			$brand_arr = explode(',',$brand);
			$brand_arr = implode('","',$brand_arr);
			$where .= ' AND i.brand in ("'.$brand_arr.'")';
		}else{
			$str = [];
			foreach($brand_list as $v){
				$str[] = '"'.$v.'"';
			}
			$where .= ' AND i.brand in('.implode($str,',').')';
		}
		if($is_remark == 1){
			$where .=" AND r.id is NOT NUll";
		}elseif($is_remark == 2){
			$where .=" AND r.id is NULL";
		}
		$brand_str_all = "('佑晟共享仓','增致牛仔 ZENGZHI','东方骆驼','米菲 MIFFY','雅鹿','法派FAPAI','安瑞井','MOYO','美丽衣橱','琴曼','GOOGIMS','ICE')";
		$brand_str = [
			'ys'=>"('增致牛仔 ZENGZHI','东方骆驼','米菲 MIFFY','雅鹿','佑晟共享仓','安瑞井','MOYO','美丽衣橱','琴曼','美丽衣橱','GOOGIMS','ICE')",
			'tj'=>"('法派FAPAI')",
			'ys_online'=>"('增致牛仔 ZENGZHI','东方骆驼','米菲 MIFFY','雅鹿','安瑞井','MOYO','美丽衣橱','GOOGIMS','ICE')",
			'tj_online'=>"('法派FAPAI')",
		];
		$case = "( CASE WHEN i.brand in ".$brand_str['ys']." THEN 'ys' WHEN i.brand in ".$brand_str['tj']." THEN 'tj' END ) company";
		$total = D('jst_inventorys')->alias('i')->join('yzm_jst_inventorys_remark r on r.other_2=i.other_2','left')->field($case.',i.id')->where($where)->group('concat(company,i.other_2)')->select();
		//$total = $inventorys->alias('i')->field('id,sum(qty) sum_qty,sum(in_qty) sum_in_qty')->where($where)->group('i.other_2')->having($having)->select();
		$total = count($total);
		//判断是否是导出数据
		if($download==0){
			$page = new page($total, 100);
			$field = $case.',i.id,i.brand,i.error_type,i.sku_name,i.other_2,s.pic,sum(s.7days) sum_7days,sum(s.30days) sum_30days,sum(i.qty) sum_qty,sum(i.order_lock) sum_order_lock,sum(i.pick_lock) sum_pick_lock,sum(i.virtual_qty) sum_virtual_qty,sum(i.purchase_qty) sum_purchase_qty,sum(i.return_qty) sum_return_qty,sum(i.in_qty) sum_in_qty,sum(i.defective_qty) sum_defective_qty,r.remark';
			$data = $inventorys->alias('i')->field($field)->join('yzm_jst_sku_sales s on s.sku_id = i.sku_id','left')->join('yzm_jst_inventorys_remark r on r.other_2=i.other_2','left')->where($where)->limit($page->limit())->order("$of $or")->group('concat(company,i.other_2)')->having($having)->select();
			//print_r($data);exit;
			$sum = $inventorys->alias('i')->join('yzm_jst_inventorys_remark r on r.other_2=i.other_2','left')->field('sum(i.qty) sum_qty,sum(i.in_qty) sum_in_qty')->where($where)->having($having)->find();
			$sum_qty = $sum['sum_qty']+$sum['sum_in_qty'];
			foreach($data as &$v){
				$filed_list = 's.enabled,i.sku_id,i.i_id,i.brand,i.error_type,i.sku_name,i.other_2,s.7days,s.30days,i.qty,i.order_lock,i.pick_lock,i.virtual_qty,i.purchase_qty,i.return_qty,i.in_qty,i.defective_qty';
				$v['inventorys_list'] = $inventorys->alias('i')->field($filed_list)->join('yzm_jst_sku_sales s on s.sku_id = i.sku_id','left')->where('i.other_2 = "'.$v['other_2'].'" and i.brand in '.$brand_str[$v['company']])->select();
			}
			include $this->admin_tpl('jst/jst_error_inventorys');
		}else{
			$number = 50000;
			$page = ceil($total/$number);
			$excel = new xlswriter('inventorys',1);
			$excel->page();
			for($i=1;$i<=$page;$i++){
				$limit = ($i-1)*$number.','.$number;
				$data = $inventorys->alias('i')->field('id,sku_id,i_id,brand,sku_name,other_2,qty,order_lock,pick_lock,virtual_qty,purchase_qty,return_qty,in_qty,defective_qty')->where($where)->order("$of $or")->limit($limit)->select();
				$excel->insert_data($data);
				unset($data);
			}
			$excel->output();
		}
	}
	
	/*箱及库位*/
	public function pack_query(){
		$sku = D('jst_sku');
		$where = '1=1';
		$brand = isset($_GET["brand"]) ? $_GET["brand"] : '';
		$pack_type = isset($_GET["pack_type"]) ? $_GET["pack_type"] : 'Bin';
		//主仓 = 1, 销退仓 = 2, 进货仓 = 3, 次品仓 = 4, 门店 = 5, 自定义1仓=6, 自定义2仓=7, 自定义3仓=8, 错误的仓库 = 0, 外仓 = 1000, 已出库 = -1, 待进仓 = -2
		$wh_names = [1=>'主仓',2=>'销退仓',3=>'进货仓',4=>'次品仓',5=>'门店',6=>'自定义1仓',7=>'自定义2仓',8=>'自定义3仓',0=>'错误的仓库',1000=>'外仓',-1=>'已出库',-2=>'待进仓',];
		if(isset($_GET['dosubmit'])){	
			$i_id = isset($_GET["i_id"]) ? $_GET["i_id"] : '';
			$sku_id = isset($_GET["sku_id"]) ? $_GET["sku_id"] : '';
			$properties_value = isset($_GET['properties_value']) ? safe_replace(trim($_GET['properties_value'])) : '';
			$sku_name = isset($_GET["name"]) ? $_GET["name"] : '';
			$other_2 = isset($_GET["other_2"]) ? $_GET["other_2"] : '';
			if($brand){
				$brand = str_replace('+',' ',$brand);
			}
		
			if($i_id) {
				if(strpos($i_id,'*') !== false){
					$i_id = trim($i_id,'*');
					$where .= ' AND i.i_id LIKE \'%'.$i_id.'%\'';
				}else{
					$where .= ' AND i.i_id = "'.$i_id.'"';
				}
			}
			if($sku_id) {
				if(strpos($sku_id,'*') !== false){
					$sku_id = trim($sku_id,'*');
					$where .= ' AND i.sku_id LIKE \'%'.$sku_id.'%\'';
				}else{
					$where .= ' AND i.sku_id = "'.$sku_id.'"';
				}
			}
			if($properties_value) {
				$where .= ' AND i.properties_value LIKE \'%'.$properties_value.'%\'';
			}
			if($sku_name) {
				$where .= ' AND i.name LIKE \'%'.$sku_name.'%\'';
			}
			if($other_2) {
				$where .= ' AND i.other_2 LIKE \'%'.$other_2.'%\'';
			}
			if($brand) {
				$brand_arr = explode(',',$brand);
				$brand_arr = implode('","',$brand_arr);
				$where .= ' AND i.brand in ("'.$brand_arr.'")';
			}else{
				$str = [];
				foreach(brand_names() as $v){
					$str[] = '"'.$v.'"';
				}
				$where .= ' AND i.brand in('.implode($str,',').')';
			}
		}
		//只有有库存的才去同步
		$where .= ' AND ii.qty > 0';
		$total = $sku->alias('i')->join('yzm_jst_inventorys ii on i.sku_id = ii.sku_id','left')->where($where)->total();
		//判断是否是导出数据
		$page = new page($total, 20);
		$field = 'i.*';
		$select_data = $sku->alias('i')->field($field)->join('yzm_jst_inventorys ii on i.sku_id = ii.sku_id','left')->where($where)->limit($page->limit())->select();
		$sku_ids_data =[];
		$company_data = ['_default'=>[],'_yalu'=>[],'_anruijing'=>[],'_meiliyichu'=>[],'_jeep'=>[],'_qiaokeli'=>[]];
		if($select_data){
			foreach($select_data as $v){
				//多聚水潭账号参数
				if($v['brand']=='雅鹿'){
					$company_data['_yalu'][] = $v['sku_id'];
				}elseif($v['brand']=='安瑞井'){
					$company_data['_anruijing'][] = $v['sku_id'];
				}elseif($v['brand']=='MOYO'){
					$company_data['_anruijing'][] = $v['sku_id'];
				}elseif($v['brand']=='美丽衣橱'){
					$company_data['_meiliyichu'][] = $v['sku_id'];
				}elseif($v['brand']=='ILOVECHOC'){
					$company_data['_qiaokeli'][] = $v['sku_id'];
				}elseif($v['brand']=='JEEP'||$v['brand']=='JEEP半成品'){
					$company_data['_jeep'][] = $v['sku_id'];
				}else{
					$company_data['_default'][] = $v['sku_id'];
				}
				$sku_ids_data[$v['sku_id']]=$v;
			}
		}
		$data = [];
		$sum_qty = 0;
		foreach($company_data as $k=>$v){
			$company = '';
			if($v){
				if($k != '_default'){
					$company = $k;
				}
				$jst = new jst($company);
				$arr = [
					'sku_ids' => $v,
					//'wms_co_id' => '',
					'pack_type' => $pack_type, //Bin,DefaultPack,Pack 
					"page_index" => 1,
					"page_size" => 200
				];
				$result = $jst->pack_query($arr);
				//print_r($v);
				//print_r($result);exit;
				if($result['code'] == 0){
					foreach($result['data']['datas'] as $val){
						if($val['qty']==0){
							continue;
						}
						$temp = $sku_ids_data[$val['sku_id']];
						$temp['bin'] = $val['bin'];
						$temp['qty'] = $val['qty'];
						$sum_qty += $val['qty'];
						$temp['modified'] = $val['modified'];
						$temp['wh_name'] = $wh_names[$val['wh_id']];
						$data[] = $temp;
					}
				}
			}
		}
		
		include $this->admin_tpl('jst/jst_pack_query');
	}
	
	
	/*订做采购单*/
	public function purchaser(){
		$of = input('get.of');
		$or = input('get.or');
		$of = in_array($of, array('qty','act_qty','finish_time','modified','confirm_date','po_id')) ? $of : 'confirm_date';
		$or = in_array($or, array('ASC','DESC')) ? $or : 'DESC';
		$status = isset($_GET["status"]) ? $_GET["status"] : 'Confirmed';
		$purchaser = D('jst_purchaser');
		$purchaser_items = D('jst_purchaser_items');
		$download = isset($_GET['download']) ? $_GET['download'] : 0;
		$company = isset($_GET['company']) ? $_GET['company'] : '';
		$where = 'company="'.$company.'"';
		if(isset($_GET['dosubmit'])){	
			$i_id = isset($_GET["i_id"]) ? $_GET["i_id"] : '';
			$po_id = isset($_GET["po_id"]) ? $_GET["po_id"] : '';
			$sku_id = isset($_GET["sku_id"]) ? $_GET["sku_id"] : '';
			$other_2 = isset($_GET["other_2"]) ? trim($_GET["other_2"]) : '';
			$name = isset($_GET["name"]) ? trim($_GET["name"]) : '';
			
			if($i_id) {
				if(strpos($i_id,'*') !== false){
					$i_id = trim($i_id,'*');
					$where .= ' AND pi.i_id LIKE \'%'.$i_id.'%\'';
				}else{
					$where .= ' AND pi.i_id = "'.$i_id.'"';
				}
			}
			if($sku_id) {
				if(strpos($sku_id,'*') !== false){
					$sku_id = trim($sku_id,'*');
					$where .= ' AND pi.sku_id LIKE \'%'.$sku_id.'%\'';
				}else{
					$where .= ' AND pi.sku_id = "'.$sku_id.'"';
				}
			}
			if($other_2){
				$where .=' AND pi.other_2 LIKE \'%'.$other_2.'#%\'';
			}
			if($name) {
				$where .= ' AND pi.name LIKE \'%'.$name.'%\'';
			}
			if($po_id){
				$where .= ' AND p.po_id = "'.$po_id.'"';
			}
		}
		if(isset($status)) {
			if($status != ''){
				$where .= ' AND p.status = "'.$status.'"';
			}
		}
		$temp = $purchaser->alias('p')->field('count(DISTINCT(p.po_id)) count')->join('yzm_jst_purchaser_items pi on pi.po_id = p.po_id','left')->where($where)->find();
		$total = $temp['count'];
		
		
		$status_arr = ['Creating'=>'草拟','WaitConfirm'=>'待审核','Confirmed'=>'已确认','Finished'=>'完成','Cancelled'=>'作废'];
		
		if($download==0){
			$page = new page($total, 100);
			$data = $purchaser->alias('p')->field('p.*,pi.name,pi.other_2')->join('yzm_jst_purchaser_items pi on pi.po_id = p.po_id','left')->where($where)->group('pi.po_id')->limit($page->limit())->order("$of $or")->select();
			include $this->admin_tpl('jst/jst_purchaser');
		}else{
			$number = 50000;
			$page = ceil($total/$number);
			$excel = new xlswriter('purchaser',1);
			$excel->page();
			for($i=1;$i<=$page;$i++){
				$limit = ($i-1)*$number.','.$number;
				$data = $purchaser->alias('p')->field('p.*,pi.name')->join('yzm_jst_purchaser_items pi on pi.po_id = p.po_id','left')->where($where)->group('pi.po_id')->limit($limit)->order("$of $or")->select();
				foreach($data as &$v){
					$v['purchaser_status'] = $status_arr[$v['status']];
					$v['purchaser_qty'] = $v['qty'];
					$v['purchaser_remark'] = $v['remark'];
					$v['purchaser_items'] = '';
					$items = $purchaser_items->field('other_2,qty')->where(['po_id'=>$v['po_id']])->select();
					foreach($items as $val){
						$item = explode('#',$val['other_2']);
						$v['purchaser_items'] .= $item[1].'*'.$val['qty'].' ';
					}
				}
				$excel->insert_data($data);
				unset($data);
			}
			$excel->output();
		}
	}
	
	/*编辑跟单*/
	public function public_purchaser_edit(){
		$field = $_GET['field'];
		$value = $_GET['value'];
		$id = $_GET['id'];
		if(!$field||!$id){
			return_json(array('status'=>0,'message'=>'参数错误！'));
		}
		$result = D('jst_purchaser')->update([$field=>$value],['id'=>$id]);
		if($result!==false){
			return_json(array('status'=>1,'message'=>L('operation_success')));
		}else{
			return_json(array('status'=>0,'message'=>L('operation_failure')));
		}
	}
	
	/*采购商品明细*/
	public function purchaser_item(){
		$po_id = $_GET['po_id'];
		$company = isset($_GET['company']) ? $_GET['company'] : '';
		if(!$po_id){
			exit('参数错误！');
		}
		$purchaser_items = D('jst_purchaser_item');
		$data = $purchaser_items->alias('pi')->field('pi.*,s.pic,s.other_2')->join('yzm_jst_sku s on s.sku_id = pi.sku_id','left')->where(['po_id'=>$po_id,'company'=>$company])->order('sku_id asc')->select();
		include $this->admin_tpl('jst/jst_purchaser_item');
	}
	
	/*跟单记录*/
	public function purchaser_log(){
		$purchaser_log = D('jst_purchaser_log');
		if(isset($_GET['dosubmit'])){
			$get =$_GET;
			if(!trim($get['po_id'])) return_json(array('status'=>0,'message'=>'参数错误！'));				
			$data = [
				'po_id'=>$get['po_id'],
				'admin_name'=>$_SESSION['admininfo']['realname'],
				'add_time'=>time(),
				'remark'=>trim($get['remark'])
			];
			
			if($get['id']){
				$result = $purchaser_log->update($data,['id'=>$get['id']]);
			}else{
				$result = $purchaser_log->insert($data);
			}
			if($result){
				return_json(array('status'=>1,'message'=>L('operation_success')));
			}else{
				return_json(array('status'=>0,'message'=>L('operation_failure')));
			}
		}
		
		
		$po_id = $_GET['po_id'];
		if(!$po_id){
			exit('参数错误！');
		}
		
		$data = $purchaser_log->where(['po_id'=>$po_id])->order('add_time asc')->select();
		include $this->admin_tpl('jst/jst_purchaser_log');
	}
	
	
	//执行全量商品更新
	public function error_inventorys_update(){
		if(getcache('LOCK::error_inventorys_update_run')){
			return_json(array('status'=>0,'message'=>'后台已在重新获取异常库存，请勿重复执行！'));
		}
		$res = D('jst_inventorys')->update(['error_type'=>0],'error_type<9');
		if($res!==false){
			//锁半天
			setcache('LOCK::error_inventorys_update_run',1,3600);
			return_json(array('status'=>1,'message'=>'操作成功，已在后台执行获取异常库存！'));
		}else{
			return_json(array('status'=>0,'message'=>'执行失败，请联系管理员！'));
		}
	}
	
	//修复工具
	public function action_diy(){
		$action = $_POST['action']??'';
		if($action == 'reget_orders'){
			$where = [];
			if($_POST['shop_id']){
				$where['shop_id'] = $_POST['shop_id'];
				delcache('LOCK::get_order_'.$_POST['shop_id']);//删除缓存
			}else{
				delcache('LOCK::*');//删除缓存
			}
			$where['begin > '] = strtotime($_POST['start'])-86400;
			$res = D('jst_log')->delete($where);//删除log表
			
			if($res!==false){
				return_json(array('status'=>1,'message'=>'操作成功，已在后台执行重新获取订单！'));
			}else{
				return_json(array('status'=>0,'message'=>'操作失败，请重试！'));
			}
		}
		include $this->admin_tpl('jst/jst_action_diy');
	}
	
	
	/**
	 * 保存配置信息
	 */
	public function save() {
		yzm_base::load_common('function/function.php', 'admin');
		if(is_ajax()){
			$arr = array();
			$config = D('config');
			foreach($_POST as $key => $value){
				if(in_array($key, array('error_log_save','site_theme','watermark_enable','watermark_name','watermark_position'))) {
					$value = safe_replace(trim($value));
					$arr[$key] = $value;
				}else{
					if($key!='site_code'){
						$value = htmlspecialchars(trim($value));
					}
				}
				$config->update(array('value'=>$value), array('name'=>$key));
			}
			set_config($arr);
			delcache('configs');
			return_json(array('status'=>1,'message'=>L('operation_success')));
		}
	}		

	private function arraySort($arr, $keys, $type = 'DESC') {
        $keysvalue = $new_array = array();
        foreach ($arr as $k => $v){
            $keysvalue[$k] = $v[$keys];
        }
        $type == 'DESC' ? arsort($keysvalue) : asort($keysvalue);
        reset($keysvalue);
        foreach ($keysvalue as $k => $v) {
           $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }

	
}